【发布时间】:2012-12-30 14:13:05
【问题描述】:
我尝试计算 R 中不同组的列均值。存在多种分配组的方法,因此创建的两列包含不同的分组。
# create a test df
df.abcd.2<-data.frame(Grouping1=c("a","f","a","d","d","f","a"),Grouping2=c("y","y","z","z","x","x","q"),Var1=sample(1:7),Var2=sample(1:7),Var3=rnorm(1:7))
df.abcd.2
现在我创建了一个包含 assign、lapply、split 和 colMeans 的循环来获取我的结果并将其存储在不同的 dfs 中。循环工作正常。
#Loop to create the colmeans and store them in dataframes
for (i in 1:2){
nam <- paste("RRRRRR",deparse(i), sep=".")
assign(nam, as.data.frame(
lapply(
split(df.abcd.2[,3:5], df.abcd.2[,i]), colMeans)
)
)
}
所以现在我想创建一个函数来将此方法应用于不同的数据帧。我的尝试看起来像这样:
# 1. function to calculate colMeans for diffrent groups
# df= desired datatframe,
# a=starting column: beginning of the columns that contain the groups, b= end of columns that contain the groups
# c=startinc column: beginning of columns to be analized, d=end of columns do be analized
function.split.colMeans<-function(df,a,b,c,d)
{for (i in a:b){
nam <- paste("OOOOO",deparse(i), sep=".")
assign(nam, as.data.frame(
lapply(
split(df[,c:d], df[,i]), colMeans)
)
)
}
}
#test the function
function.split.colMeans(df.abcd.2,1,2,3,5)
因此,当我测试此功能时,我既没有收到错误消息也没有收到结果...谁能帮帮我吗?
【问题讨论】:
-
您确定您真的想将结果存储在不同的对象中吗?我在这里的两分钱就是在列表中做所有事情。
-
@RomanLuštrik 。我理解你的意思吗,你会写一个循环来将所有结果存储在一个列表中?我试着听从你的建议,并使用了 plyr 包中的 dlply 。所以我的函数看起来像
function.list<-function(x,a,b){for (i in a:b){dlply(x,.(x[,i]),colwise(mean))}}。但不幸的是,它不适用于循环。能否提供更多信息?