Exercises

These exercises accompany the Writing Functions, Conditionals and Loops tutorial.

  1. Write a function that converts ozone concentrations from ppm to ppb and then converts from ppb to ug/m3 (multiply ppb by 1.96 to account for molecular mass of O3 and molar volume). Check your answer by converting the first ozone value in the dataset.

  2. Examine the following code. Can you describe what the following lapply() function is doing? Note that list.file() is a built-in function, you can see what it does by using ?list.file

my.file.path <- c("datasets/session4/")

get.my.files <- lapply(list.files(path = my.file.path, pattern = ".csv"),
                       
                       function(x) read.csv(paste(my.file.path, x, sep=""), header=TRUE)

comb.files <- do.call(rbind, get.my.files)  #do.call just evaluates 
#what is inside the function.  So rbind is what is interesting here.


Solutions


Solution 1

convert03 <- function(x){
  ppb <- x * 1000
  ug <- ppb * 1.96
  ug
}

library(region5air)
data(chicago_air)
convert03(chicago_air$ozone[1])
## [1] 62.72

Solution 2

The goal of this function is to search a folder and find all of the csv files in that folder. It then reads them all in using read.csv() and rbinds them into one large list. This can then be converted to one large dataset. This could be very useful for a lot of monitoring or modeling data that is often spread out in many files that are of a similar type.

my.file.path <- c("E:/RIntro/datasets/session4/")

get.my.files <- lapply(list.files(path = my.file.path,
                      pattern = ".csv"), 
# This line is using list.file to create a list of all the csv files.  list.file() is supplying this information to the first argument in lapply
                function(x) read.csv(paste(my.file.path, x, 
                                       sep=""), header=TRUE)) 
# This line is taking the list of files and feeding it into the read.csv 
#function which will read in all the csv files that were created by list.files
      
comb.files <- do.call(rbind, get.my.files)  # The rbind function is binding 
#the two data frames created by read.csv into one large data frame.