This is my WPA for this week
a <- 5
b <- 10
paste("The number a is", a, "and the number b is", b)
## [1] "The number a is 5 and the number b is 10"
x <- c(1, 4, -2, 1, 4, -5, 10)
# logical vector of positive values
pos.log <- x > 0
pos.log
## [1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE
# Now use the logical vector to create a vector of ONLY positive values from x
x.pos <- x[pos.log] # Give me the values of x for which pos.log is TRUE
x.pos
## [1] 1 4 1 4 10
Q1
#Captain Jack is convinced that he can predict how much gold he will find on an island with the following equation: (a * b) - c * 324 + log(a), where a is the area of the island in square meters, b is the number of trees on the island, and c is how drunk he is on a scale of 1 to 10. Create a function called Jacks.Equation that takes a, b, and c as arguments and returns Captain Jack’s predictions. Test your function for an island with an area of 1,000 square meters that contains 30 trees when Jack is at a 7 on a drunkenness scale.
jacks.equation <- function(a,
b,
c) {
output <- (a * b) - c * 324 + log(a)
return(output)
}
jacks.equation(a = 1000, b = 30, c = 7)
## [1] 27738.91
Q2
#Write a function called standardize.me that takes a vector x as an argument, and returns a vector that standardizes the values of x (standardization means subtracting the mean and dividing by the standard deviation).
standardize.me <- function(x) {
output <- c((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
Q3
#Write a function called how.many that takes two arguments (data and value). The function should return a value indicating how many times the element value occurred in the vector data
how.many <- function(x,
value) {
output <- length(x[x == value])
return(output)
}
data2 <- c(1, 1, 9, 3, 2, 1, 1)
how.many(data2, 1)
## [1] 4
Q4
#Often times you will need to recode values of a dataset. For example, if you have a survey of age data, you may want to convert any crazy values (like anything below 0 or above 100) to NA. Let’s create a function to do this in R. Write a function called recode.numeric() with 3 arguments: x, lb, and ub. We’ll assume that x is a numeric vector. The function should look at the values of x, convert any values below lb and above ub to NA, and then return the resulting vector
recode.numeric <- function(x, lb, ub) {
x[x < lb] <- NA
x[x > ub] <- NA
output <- x
return(output)
}
recode.numeric(x = c(5, 6, -10, 2, 1000, 2), lb = 0, ub = 100)
## [1] 5 6 NA 2 NA 2