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

可紊 提交于 2019-12-19 14:05:15

问题


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?


回答1:


Try:

x <- c("supp", "dose") 
ddply(ToothGrowth, x, function(df) mean(df$len)) 


来源:https://stackoverflow.com/questions/3784187/how-to-use-string-variables-to-create-variables-list-for-ddply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!