Homework1:Introduction to R

Quetion1: Try using the functions sum() and length() to calculate the mean amount of rainfall, check your answer using the mean function.

rain <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
mean(rain) == sum(rain)/length(rain)
## [1] TRUE

[1] TRUE

Question2:Using the four steps above compute the standard deviation of the rainfall data. You have the correct answer if you get something close to 3.4

rain <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
a <- rain - mean(rain)
b <- a^2
d <- mean(b)
e <- sqrt(d)

print(e)
## [1] 3.394

[1] 3.394

Question3 Now,complete the return statement below to create a function to convert inches to centimeters. Assume the input data are in inches and you want to return the same data converted to cm.

AInches <- c(1, 2, 3, 4, 5, 6)

in_to_cm <- function(AInches) {
    conv_Factor <- 0.3937
    return(AInches/conv_Factor)
}
ACm <- in_to_cm(AInches)
print(ACm)
## [1]  2.54  5.08  7.62 10.16 12.70 15.24

[1] 2.54 5.08 7.62 10.16 12.70 15.24

Question4:Write a function to compute the standard deviation, use the four steps outlined above. Do not use the internal sd() function to check your work because it uses SD=sqrt(1(xi-x_bar)2), note the N-1 in the denominator. Your function is correct if you find a standard deviation of around 3.39.

rain <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)

standard_dev <- function(dataset) {
    return(sqrt(mean(((dataset - mean(dataset))^2))))
}
standard_dev(rain)
## [1] 3.394