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
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.