This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
Jacks.gold <- function(area,trees,drunkness) {
output <- (area * trees) - drunkness*324 + log(area)
return(output)
}
Jacks.gold(area = 1000, trees = 30, drunkness = 7)
## [1] 27738.91
standardize.me <- function(x) {
output <- (x - mean(x)) / sd(x)
return(output)
}
data <- c(6, 3, 8, 6, 3, 2, 3, 2, 100)
standardize.me(data)
## [1] -0.2740789 -0.3677514 -0.2116305 -0.2740789 -0.3677514 -0.3989756
## [7] -0.3677514 -0.3989756 2.6609937
how.many <- function(data, value) {
output <- table(data == value)
return(output)
}
how.many(data = c(1, 1, 9, 3, 2, 1, 1), value = 1)
##
## FALSE TRUE
## 3 4
how.many(data = c(1, 1, 9, 3, 2, 1, 1), value = -100)
##
## FALSE
## 7
recode.numeric <- function(x, lb, ub) {
(outliers <- x > ub | x < lb)
x[outliers] <- NA
return(x)
}
recode.numeric(x = c(5, 6, -10, 2, 1000, 2), lb = 0, ub = 100)
## [1] 5 6 NA 2 NA 2
survey <- data.frame(
id = 1:6,
q1 = c(6, 2, 5, -1, 11, 100),
q2 = c(-5, 4, 65, 3, 7, 6),
q3 = c(2, 1, 2, 45, 5, -5)
)
####copy the dataframe:
survey.fixed <- data.frame(
id = 1:6,
q1 = c(6, 2, 5, -1, 11, 100),
q2 = c(-5, 4, 65, 3, 7, 6),
q3 = c(2, 1, 2, 45, 5, -5)
)
survey.fixed$id<- recode.numeric(survey$id, lb = 1, ub = 10)
survey.fixed$q1<- recode.numeric(survey$q1, lb = 1, ub = 10)
survey.fixed$q2<- recode.numeric(survey$q2, lb = 1, ub = 10)
survey.fixed$q3<- recode.numeric(survey$q3, lb = 1, ub = 10)
survey.fixed
## id q1 q2 q3
## 1 1 6 NA 2
## 2 2 2 4 1
## 3 3 5 NA 2
## 4 4 NA 3 NA
## 5 5 NA 7 5
## 6 6 NA 6 NA
orders <- c("coke light",
"coke",
"pepsi",
"coke",
"coke light",
"water",
"pepsi",
"pepsi light",
"water",
"water")
old <- c("coke", "coke light", "water")
new <- c("Pepsi", "Pepsi light", "Pepsi Max")
recode.factor <- function(x, old,new) {
x[x == old[1]] <- new[1]
x[x == old[2]] <- new[2]
x[x == old[3]] <- new[3]
return(x)
}
recode.factor(orders, old = c("coke", "coke light", "water"),
new = c("Pepsi", "Pepsi light", "Pepsi Max") )
## [1] "Pepsi light" "Pepsi" "pepsi" "Pepsi" "Pepsi light"
## [6] "Pepsi Max" "pepsi" "pepsi light" "Pepsi Max" "Pepsi Max"
madlib <- function(adjective, name, plural.noun) {
output <- paste("If you talk to an", adjective, "pirate like", name, "you may find that he/she spends more time talking about",plural.noun, "than the pirate arts" )
return (output)}
madlib(adjective = "hipster", name = "Bruce", plural.noun = "kale")
## [1] "If you talk to an hipster pirate like Bruce you may find that he/she spends more time talking about kale than the pirate arts"