How to Use the Formula Interface in R
How to Add Lines to a Plot in R
How to Use Data in Tall Format in Lattice Plots in R

How to Simplify Results (or Not) with the sapply Function in R

The sapply() function doesn’t always return a vector. In fact, the standard output of sapply is a list, but that list gets simplified to either a matrix or a vector if possible.

  • If the result of the applied function on every element of the list or vector is a single number, sapply() simplifies the result to a vector.

  • If the result of the applied function on every element of the list or vector is a vector with exactly the same length, sapply() simplifies the result to a matrix.

  • In all other cases, sapply() returns a (named) list with the results.

Say you want to know the unique values of every variable in the data frame clients. To get all unique values in a vector, you use the unique() function. You can get the result you want by applying that function to the data frame clients like this:

> sapply(clients, unique)
$hours
[1]  25 110 125  40
$public
[1]  TRUE FALSE
$type
[1] "public"  "abroad"  "private"

In the variable hours, you find four unique values; in the variable public, only two; and in the variable type, three. Because the lengths of the result differ for every variable, sapply() can’t simplify the result, so it returns a named list.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Extract Data from Plots in R
How to Test Data Normality Graphically in R
How to Read Errors and Warnings in R
How to Use If…Else Statements in R
How to Use the R Help Files
Advertisement

Inside Dummies.com