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

How to do it...

To apply a function to all elements of a collection with lapply and sapply, follow these instructions:

  1. Operate on a simple vector:
> lapply(c(1,2,3), sqrt) 
 
[[1]] 
[1] 1 
 
[[2]] 
[1] 1.414214 
 
[[3]] 
[1] 1.732051 
  1. Use lapply and sapply to calculate the means of a list of collections:
> x <- list(a = 1:10, b = c(1,10,100,1000),     c=seq(5,50,by=5)) 
> lapply(x, mean) 
 
$a 
[1] 5.5 
$b 
[1] 277.75 
$c 
[1] 27.5 
 
> class(lapply(x,mean)) 
[1] "list" 
 
> sapply(x, mean) 
 
     a      b      c 
  5.50 277.75  27.50 
 
> class(sapply(x,mean)) 
 
[1] "numeric"
  1. Calculate the minimum value for each variable in the auto data frame:
> sapply(auto[,2:8], min) 
         mpg    cylinders displacement   horsepower 
           9            3           68           46 
      weight acceleration   model_year 
        1613            8           70 

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