Learning R in Practice

Advanced Functions

Apply

The apply is a family functions crucial for R applications. The core functionality is to apply the same procedure to all elements in a data structure. Or in more complicated situation, it is Split-Apply-Combine strategy.

lapply

l in lapply stands for list. It will read in a list and apply the given function to each element in that list and combine the individual result into a new list.

To find the class of each element in a list, we could use the following command:

lapply(a_list, class)

sapply

s in sapply stands for simplify. Comparing to lapply, it will reduce the output list to a vector if possible.

vapply

vapply is used to specify the type of each element. And

vapply(a_list, class, as.character)

tapply

tapply can tabulate the result according to the extra index (factor-like variable) specified in the input.

tapply(a_list, index, class)

replicate

Besides apply series functions, replicate function will run the given function with a specified times.

Random number and sampling

Sample

sample function can easily generate a sampling from the given list with replace feature and specified probability prob.

sample(a_list, num, replace=TRUE, prob

random number

In R, there is a series random function with ?+distribution. Distribution is the statistical distribution want to implement, and ? has the following options:

  • r return random numbers
  • d return density
  • p return probability
  • q return quantile