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 functions to subsets of a vector, follow these steps:

  1. Calculate mean mpg for each cylinder type:
> tapply(auto$mpg,auto$cylinders,mean) 
 
    3cyl     4cyl     5cyl     6cyl     8cyl 
20.55000 29.28676 27.36667 19.98571 14.96311 
  1. We can even specify multiple factors as a list. The following example shows only one factor, since the out file has only one, but it serves as a template that you can adapt:
> tapply(auto$mpg,list(cyl=auto$cylinders),mean) 
 
cyl 
    3cyl     4cyl     5cyl     6cyl     8cyl 
20.55000 29.28676 27.36667 19.98571 14.96311  

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