Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string variables to create variables list for ddply?

Tags:

r

plyr

Using R's builtin ToothGrowth example dataset, this works:

ddply(ToothGrowth, .(supp,dose), function(df) mean(df$len)) 

But I would like to have the subsetting factors be variables, something like

factor1 = 'supp'
factor2 = 'dose'
ddply(ToothGrowth, .(factor1,factor2), function(df) mean(df$len)) 

That doesn't work. How should this be done?

I thought perhaps something like this:

factorCombo = paste('.(',factor1,',',factor2,')', sep='') 
ddply(ToothGrowth, factorCombo, function(df) mean(df$len)) 

But it doesn't work either. I think I am close, but not sure the proper way to do it. I suppose the entire command could be put into a string, followed by an eval() call of the string, but hopefully is there a more elegant way?

like image 741
Alex Holcombe Avatar asked Sep 24 '10 04:09

Alex Holcombe


1 Answers

Try:

x <- c("supp", "dose") 
ddply(ToothGrowth, x, function(df) mean(df$len)) 
like image 121
Brandon Bertelsen Avatar answered Nov 10 '22 21:11

Brandon Bertelsen