Reputation: 69
I have the following list:
x<-
[[1]]
[[1]][[1]]
Band n
1: A 4
2: B 14
3: C 148
4: D 207
[[1]][[2]]
Band n
1: A 4
2: B 13
3: C 151
4: D 207
[[1]][[3]]
Band n
1: A 4
2: B 13
3: C 152
4: D 207
[[1]][[4]]
Band n
1: A 4
2: B 13
3: C 156
4: D 207
[[2]]
[[2]][[1]]
Band n
1: A 4
2: B 14
3: C 148
4: D 207
[[2]][[2]]
Band n
1: A 4
2: B 13
3: C 153
4: D 207
[[2]][[3]]
Band n
1: A 4
2: B 13
3: C 155
4: D 207
[[2]][[4]]
Band n
1: A 4
2: B 12
3: C 158
4: D 207
which you can obtain by:
x <- list(list(structure(list(Band = c("A", "B", "C", "D"), n = c(4L, 14L, 148L,
207L)), row.names = c(NA,
-4L), class = c("data.table", "data.frame")),
structure(list(Band = c("A", "B", "C", "D"), n = c(4L, 13L, 151L,
207L
)), row.names = c(NA, -4L), class = c("data.table", "data.frame"
)), structure(list(
Band = c("A", "B", "C", "D"), n = c(4L, 13L, 152L, 207L
)), row.names = c(NA,
-4L), class = c("data.table", "data.frame")),
structure(list(Band = c("A", "B", "C", "D"), n = c(4L, 13L, 156L,
207L
)), row.names = c(NA, -14L), class = c("data.table", "data.frame"
))), list(
structure(list(Band = c("A", "B", "C","D"), n = c(4L, 14L, 148L,
207L
)), row.names = c(NA, -4L), class = c("data.table", "data.frame"
)), structure(list(
Band = c("A", "B", "C", "D"), n = c(4L, 13L, 153L, 207L
)), row.names = c(NA,
-4L), class = c("data.table", "data.frame")),
structure(list(Band = c("A", "B", "C", "D"), n = c(4L, 13L, 155L,
207L
)), row.names = c(NA, -4L), class = c("data.table", "data.frame"
)), structure(list(
Band = c("A", "B", "C", "D"), n = c(4L, 12L, 158L, 207L
)), row.names = c(NA,
-4L), class = c("data.table", "data.frame"))))
I need to get the mean of n, per Band, for the same time period, meaning:
mean([[1]][[1]], [[2]][[1]])
mean([[1]][[2]], [[2]][[2]])
I would know how to do it with a ''' do.call(cbind, x)''' if the Band column was not there. But like that I have lists of data tables.
Upvotes: 2
Views: 62
Reputation: 102920
Here is a base R option using aggregate
+ asplit
Map(
function(x) aggregate(n ~ ., do.call(rbind, x), mean),
asplit(do.call(cbind, x), 1)
)
which gives
[[1]]
Band n
1 A 4
2 B 14
3 C 148
4 D 207
[[2]]
Band n
1 A 4
2 B 13
3 C 152
4 D 207
[[3]]
Band n
1 A 4.0
2 B 13.0
3 C 153.5
4 D 207.0
[[4]]
Band n
1 A 4.0
2 B 12.5
3 C 157.0
4 D 207.0
Upvotes: 1
Reputation: 887991
Perhaps we can do a transpose
library(purrr)
library(data.table)
library(magrittr)
transpose(x) %>%
map(~ rbindlist(.x)[, .(n = mean(n)), Band])
-output
#[[1]]
# Band n
#1: A 4
#2: B 14
#3: C 148
#4: D 207
#[[2]]
# Band n
#1: A 4
#2: B 13
#3: C 152
#4: D 207
#[[3]]
# Band n
#1: A 4.0
#2: B 13.0
#3: C 153.5
#4: D 207.0
#[[4]]
# Band n
#1: A 4.0
#2: B 12.5
#3: C 157.0
#4: D 207.0
Upvotes: 1