What is the difference between the functions apply(), lapply(), sapply(), and tapply()?

While all these functions allow iterating over a data structure without using loops and perform the same operation on each element of it, they are different in terms of the type of input and output and the function they perform.

  • apply()—takes in a data frame, a matrix, or an array and returns a vector, a list, a matrix, or an array. This function can be applied row-wise, column-wise, or both.
  • lapply()—takes in a vector, a list, or a data frame and always returns a list. In the case of a data frame as an input, this function is applied only column-wise.
  • sapply()—takes in a vector, a list, or a data frame and returns the most simplified data structure, i.e., a vector for an input vector, a list for an input list, and a matrix for an input data frame.
  • tapply()—calculates summary statistics for different factors (i.e., categorical data).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *