I am populating lists in a for()
loop. A sample of the result is included below.
dta <- list(structure(c(128L, 175L), .Dim = 2L, .Dimnames = structure(list(
c("0", "1")), .Names = ""), class = "table"), structure(c(132L,
171L), .Dim = 2L, .Dimnames = structure(list(c("0", "1")), .Names = ""), class = "table"),
structure(c(130L, 173L), .Dim = 2L, .Dimnames = structure(list(
c("0", "1")), .Names = ""), class = "table"), structure(c(133L,
170L), .Dim = 2L, .Dimnames = structure(list(c("0", "1")), .Names = ""), class = "table"))
Each list shows the number of 0's and 1's for a given data set.
> head(dta)
[[1]]
0 1
128 175
[[2]]
0 1
132 171
[[3]]
0 1
130 173
[[4]]
0 1
133 170
The lapply()
function that I am accustomed to using operates within the lists (i.e. finds the sum of the elements within a given list). Here I want the average across lists. Equivocally, I want the mean number of 0's and 1's that occurred in each list (i.e. to average the 0's I want the sum of 128,132,130,133 divide by 4).
Any suggestions would be appreciated.
You could try
library(reshape2)
library(data.table)
setDT(melt(dta))[, mean(value), Var1]
Or
colMeans(do.call(rbind, dta))
You can use tapply()
u <- unlist(dta)
tapply(u, names(u), mean)
# 0 1
# 130.75 172.25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With