Question 1
drunk <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
jacks.equation <- function(squaremeters = 0,
trees = 0,
drunk = 0) {
output <- squaremeters * trees - drunk * 324 + log(squaremeters)
return(output)}
jacks.equation(squaremeters = 1000,
trees = 30,
drunk = 7)
## [1] 27738.91
Question 2
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
Question 3
how.many <- function(data, value){
result <- sum(data == value)
return(result)
}
how.many(data = c(1, 1, 9, 3, 2, 1, 1), value = 1)
## [1] 4
how.many(data = c(1, 1, 9, 3, 2, 1, 1), value = -100)
## [1] 0
Question 4
recode.numeric <- function(x, lb, ub) {
outliers <- x < lb | x > ub
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.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.fixed$id, lb = 1, ub = 10)
survey.fixed$q1 <- recode.numeric(survey.fixed$q1, lb = 1, ub = 10)
survey.fixed$q2 <- recode.numeric(survey.fixed$q2, lb = 1, ub = 10)
survey.fixed$q3 <- recode.numeric(survey.fixed$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
Question 5
orders <- c("coke light",
"coke",
"pepsi",
"coke",
"coke light",
"water",
"pepsi",
"pepsi light",
"water",
"water")
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"
Question 6
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.", sep = "")
return(output)}
madlib("hipster", "Bruce", "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."
Question 7
remove.outliers <- function(x) {
out.log <- x > (mean(x) + 2 * sd(x)) | x < (mean(x) - 2 * sd (x))
return(x[out.log == FALSE])}
data <- c(rep(1, 50), -529484903)
remove.outliers(data)
## [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## [36] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Question 8 (started)
ttest.apa <- function(x, null, p.critical) {
test.result <- t.test(x, mu = null)
test.statistic <- round(test.result$statistic, 2)
df <- round(test.result$parameter, 2)
p.value <- round(test.result$.p.value, 2) }