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

Applying a function on groups from a data frame

In the following example, we find the correlation between mpg and weight for each cylinder type:

> by(auto, auto$cylinders, function(x) cor(x$mpg, x$weight)) 
auto$cylinders: 3cyl 
[1] 0.6191685 
--------------------------------------------------- 
auto$cylinders: 4cyl 
[1] -0.5430774 
--------------------------------------------------- 
auto$cylinders: 5cyl 
[1] -0.04750808 
--------------------------------------------------- 
auto$cylinders: 6cyl 
[1] -0.4634435 
--------------------------------------------------- 
auto$cylinders: 8cyl 
[1] -0.5569099

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