Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R数据帧列表上的平均值_R - Fatal编程技术网

R数据帧列表上的平均值

R数据帧列表上的平均值,r,R,如果我在R中有一个数据帧列表,例如: x<-c(1:10) y<-2*x z<-3*x df.list <- list(data.frame(x),data.frame(y),data.frame(z)) 等 因此output[i,1]=(dfone[i,1]+dftwo[i,1]+dfthree[i,1])/3 在for循环中执行此操作非常简单: for (i in 1:length(dfone)) { dfoutput[i,'value']=(dfone[i,'

如果我在R中有一个数据帧列表,例如:

x<-c(1:10)
y<-2*x
z<-3*x
df.list <- list(data.frame(x),data.frame(y),data.frame(z))

因此
output[i,1]=(dfone[i,1]+dftwo[i,1]+dfthree[i,1])/3

在for循环中执行此操作非常简单:

for (i in 1:length(dfone))
{
  dfoutput[i,'value']=(dfone[i,'value']+dftwo[i,'value']+dfthree[i,'value'])/3
}

但我相信一定有更优雅的方式吗?

在问题变成其他问题后编辑。这回答了你的问题吗

dfs <- list(dfone, dftwo, dfthree)

#oneliner
res <- rowMeans(sapply(dfs,function(x){
  return(x[,"val"])
}))

#in steps

#step one: extract wanted column from all data
#this returns a matrix with one val-column for each df in the list
step1 <- sapply(dfs,function(x){
  return(x[,"val"])
})

#step two: calculate the rowmeans. this is self-explanatory
step2 <- rowMeans(step1)


#or an even shorter oneliner with thanks to@davidarenburg:

rowMeans(sapply(dfs, `[[`, "value"))

dfs哪个列?每个
数据框都只有一列,因此您可能需要创建一个更具代表性的示例。您想要数据框中每列的总体平均值还是?期望的输出是什么?问题是for循环非常慢(至少在我在R中看到的情况下),所以我试图避免这种情况。您的描述令人困惑。这就是我不理解这些解释的原因。如果你发布“这就是我现在拥有的”,“这就是我想要的”。不会有混乱。只需发布示例产生的输出。尝试
Reduce(“+”,list(dfone,dftwo,dfthree))/3
其中3是
list
的长度或我们放置在
列表中的数据帧数。我不是想做
mean(dfone$x[1:n])
,而是想
mean(df[1-5]$x[1])
,如果你明白我的意思:)如果你把它作为你的预期输出添加,那会有所帮助,因为没有人这样解释它。你能用相关的样本数据和基于此的预期输出更新你的问题吗?谢谢。它看起来确实能胜任这项工作——你能解释一下它对我做了什么吗?谢谢你可以简化为只
rowMeans(sapply(dfs,`[`,“value”))
它没有。它只获取值。正如你所看到的,step2有一个函数
rowMeans
。那会怎么样?很抱歉,这是非常基本的R。
for (i in 1:length(dfone))
{
  dfoutput[i,'value']=(dfone[i,'value']+dftwo[i,'value']+dfthree[i,'value'])/3
}
dfs <- list(dfone, dftwo, dfthree)

#oneliner
res <- rowMeans(sapply(dfs,function(x){
  return(x[,"val"])
}))

#in steps

#step one: extract wanted column from all data
#this returns a matrix with one val-column for each df in the list
step1 <- sapply(dfs,function(x){
  return(x[,"val"])
})

#step two: calculate the rowmeans. this is self-explanatory
step2 <- rowMeans(step1)


#or an even shorter oneliner with thanks to@davidarenburg:

rowMeans(sapply(dfs, `[[`, "value"))