Section 10 Function lapply
& sapply
10.1 Usage
lapply(X, FUN, ...)
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE)
10.2 Arguments
?lapply
X
is a vector
FUN
the function to be applied
...
optional arguments to FUN
simplify
is logical
The function sapply
is a user-friendly version and wrapper of lapply by default returning a vector, matrix or array
The function vapply
is similar to sapply
, but has a pre-specified type of return value, so it can be safer (and sometimes faster) to use.
10.3 Steps
The function lapply
provides a for
loop like action
it loops over a list, iterating over each element in that list
it applies a function to each element of the list (a function that you specify)
and returns a list
10.4 lapply
on a vector
Example 1
xvec <- 1:5
lapply(xvec, FUN = sqrt)
lapply(xvec, FUN = log)
sapply(xvec, FUN = sqrt)
sapply(xvec, FUN = log)
Example 2
10.8 Create a summary statistics
# Data
set.seed(1234)
id <- paste0('S',1:20)
age <- sample(x = 8:10, size = length(id), replace = TRUE)
wt <- sample(30:40, size = length(id), replace = TRUE)
sex <- sample(x = c('Male','Female'), size = length(id), replace = TRUE)
vac <- sample(c(T,F), size = length(id), replace = TRUE)
DF <- data.frame(ID=id, Age=age, Wt=wt,
Sex=sex, Vac=vac, stringsAsFactors = TRUE)
DF$Age[5] <- NA
DF$Wt[10] <- NA
str(DF)
# Using the fnSummary created earlier
sapply(names(DF)[2:3],
FUN = function(x) fnSummary(DF[,x], na.rm=TRUE))
}