O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

One caution

As we mentioned earlier, the output type of sapply depends on the input object. However, because of how R operates with data frames, it is possible to get an unexpected output:

> sapply(auto[,2:6], min) 
 
         mpg    cylinders displacement   horsepower       weight 
           9            3           68           46         1613 

In the preceding example, auto[,2:6] returns a data frame, and hence the input to sapply is a data frame object. Each variable (or column) of the data frame is passed as an input to the min function, and we get the output as a vector with column names taken from the input object. Try this:

> sapply(auto[,2], min) [1] 28.0 19.0 36.0 28.0 21.0 23.0 15.5 32.9 16.0 13.0 12.0 30.7 [13] 13.0 27.9 13.0 23.8 29.0 14.0 14.0 29.0 20.5 26.6 20.0 20.0 [25] 26.4 16.0 40.8 15.0 18.0 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required