KEY VERSION
This homework assignment will test your overall R know-how, and allow you to practice using RMarkdown.
Complete the following tasks in a new R markdown script in R studio. For each question, first give a brief description (e.g., “Question 1: calculate the lowest miles/gallon in mtcars”), and then provide R code using "```" and the echo = TRUE argument. When finished, Knit your script together into an html report.
mtcars dataset? Print this value to the screen.min(mtcars$mpg)
## [1] 10.4
# or
min(mtcars[,1])
## [1] 10.4
mtcars dataset, make a new dataframe called cars.new that has only two columns: the miles per gallon and the number of cylinders.cars.new <- data.frame(mtcars$mpg,mtcars$cyl)
# or
cars.new <-mtcars[,1:2]
sum(cars.new$mpg>=20)
## [1] 14
cars.new object, coerce the cyl column into a factor.cars.new$cyl <-as.factor(cars.new$cyl)
cars.new.hist(cars.new$mpg)
myFunc that calculates the min, max, and mean of a vector, and returns those values in a new vector.myfunc <- function(xvec){
xmin <- min(xvec)
xmax <- max(xvec)
xmean <- mean(xvec)
return(c(xmin,xmax,xmean))
}
mtcars dataset (mpg).myfunc(mtcars[,1])
## [1] 10.40000 33.90000 20.09062
for loop that uses your new function to caclulate the min, max, and mean for each column in the mtcars dataset, printing the answer to the screen as it goes.for (i in 1:ncol(mtcars)){
print(myfunc(mtcars[,i]))
}
## [1] 10.40000 33.90000 20.09062
## [1] 4.0000 8.0000 6.1875
## [1] 71.1000 472.0000 230.7219
## [1] 52.0000 335.0000 146.6875
## [1] 2.760000 4.930000 3.596563
## [1] 1.51300 5.42400 3.21725
## [1] 14.50000 22.90000 17.84875
## [1] 0.0000 1.0000 0.4375
## [1] 0.00000 1.00000 0.40625
## [1] 3.0000 5.0000 3.6875
## [1] 1.0000 8.0000 2.8125
apply to calculate the min, max, and mean of each column in mtcars using your new function myfunc.apply(mtcars,2,myfunc)
## mpg cyl disp hp drat wt qsec vs am
## [1,] 10.40000 4.0000 71.1000 52.0000 2.760000 1.51300 14.50000 0.0000 0.00000
## [2,] 33.90000 8.0000 472.0000 335.0000 4.930000 5.42400 22.90000 1.0000 1.00000
## [3,] 20.09062 6.1875 230.7219 146.6875 3.596563 3.21725 17.84875 0.4375 0.40625
## gear carb
## [1,] 3.0000 1.0000
## [2,] 5.0000 8.0000
## [3,] 3.6875 2.8125