0

I have 25 data frames in the form of a list like this(three shown here, three is sufficient for sample calculations):

df1 <- data.frame(c(1, 3, 2, 4, 2, 2,4), c(4, 5, 2, 5, 6, 3, 2))
df2 <- data.frame(c(4, 2, 5, 2, 5, 2, 6), c(6, 3, 2, 6, 2, 6, 3))
df3 <- data.frame(c(1, 3, 2, 4, 2, 2,4), c(4, 5, 2, 5, 6, 3, 2))
list <- list(df1, df2, df3)

I want to make another data frame which contains the average value in each cell, and next to that I want the standard deviation. So it will be a 4 column by 7 row data frame which contains mean and standard deviation of each cell in the data frame.

How can this be done? My data also has way more than 7 rows.

d.b
  • 32,245
  • 6
  • 36
  • 77
Jack Arnestad
  • 1,845
  • 13
  • 26
  • 1
    It would be helpful to include the desired output for this input so that possible solutions can be verified. – MrFlick Dec 01 '17 at 21:37

2 Answers2

2

I admit I am fair impressed by d.b's answer, but I think this problem might be better managed by turning your list into a 3d array.

library(abind)

a <- abind(mylist, along = 3)
a <- apply(a, c(1,2), function(i) abind(c(mean(i), sd(i)), along = 2))

data.frame(t(rbind(a[, , 1], a[, , 2])))

Result

      X1        X2       X3        X4
2.000000 1.5491933 4.666667 1.0327956
2.666667 0.5163978 4.333333 1.0327956
3.000000 1.5491933 2.000000 0.0000000
3.333333 1.0327956 5.333333 0.5163978
3.000000 1.5491933 4.666667 2.0655911
2.000000 0.0000000 4.000000 1.5491933
4.666667 1.0327956 2.333333 0.5163978
1
mylist <- list(df1, df2, df3)
do.call(cbind, lapply(lapply(1:2, function(i) sapply(mylist, function(x) x[,i])),
                      function(a) t(apply(a, 1, function(x) c(mean(x), sd(x))))))
#         [,1]      [,2]     [,3]      [,4]
#[1,] 2.000000 1.7320508 4.666667 1.1547005
#[2,] 2.666667 0.5773503 4.333333 1.1547005
#[3,] 3.000000 1.7320508 2.000000 0.0000000
#[4,] 3.333333 1.1547005 5.333333 0.5773503
#[5,] 3.000000 1.7320508 4.666667 2.3094011
#[6,] 2.000000 0.0000000 4.000000 1.7320508
#[7,] 4.666667 1.1547005 2.333333 0.5773503
d.b
  • 32,245
  • 6
  • 36
  • 77