如何在许多data.frame列中获得列表的平均值

时间:2014-11-03 18:17:54

标签: r

dput(head(P[,1:2],12))

structure(list(valoracion.c1 = list(c(0.75, 1, 1), c(0.75, 1, 
1), c(0.75, 1, 1), c(0.75, 1, 1), c(0.75, 1, 1), c(0.5, 0.75, 
1), c(0.75, 1, 1), c(0.75, 1, 1), c(0.5, 0.75, 1), c(0.75, 1, 
1), c(0.5, 0.75, 1), c(0.75, 1, 1)), valoracion.c2 = list(c(0.75, 
1, 1), c(0.75, 1, 1), c(0.5, 0.75, 1), c(0.75, 1, 1), c(0.75, 
1, 1), c(0.75, 1, 1), c(0.5, 0.75, 1), c(0.75, 1, 1), c(0.25, 
0.5, 0.75), c(0.25, 0.5, 0.75), c(0.75, 1, 1), c(0.5, 0.75, 1
))), .Names = c("valoracion.c1", "valoracion.c2"), row.names = c(NA, 
12L), class = "data.frame")

我想获得每列的平均值并保留数据结构。我试过

像这样的东西

  

dat2< - P [1,]   dat2 []&lt ;-( lapply(P,function(x)list(Reduce(mean,x))))    显示追溯

重新运行Debug  mean.default(init,x [[i]])出错:   'trim'必须是长度为1的数字

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

假设您显示的数据类似于下面的数据:

dat2 <- dat1[1,]
dat2[] <- lapply(dat1, function(x) list(Reduce(`+`, x)))
dat2
#       Col1       Col2       Col3
#1 18, 19, 23 20, 15, 25 22, 21, 17


head(dat1,3)
#    Col1    Col2    Col3
#1 2, 1, 3 2, 1, 3 2, 3, 1
#2 2, 1, 3 3, 1, 2 1, 3, 2
#3 1, 2, 3 3, 1, 2 2, 3, 1

数据

set.seed(45)
dat1 <- data.frame(Col1=I(lapply(1:10, function(i) sample(3))),
    Col2=I(lapply(1:10, function(i) sample(3))),
    Col3= I(lapply(1:10, function(i) sample(3))))