Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to generate averages across multiple lists

Tags:

list

r

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.

like image 491
B. Davis Avatar asked Jan 18 '15 20:01

B. Davis


2 Answers

You could try

library(reshape2)
library(data.table)
setDT(melt(dta))[, mean(value), Var1]

Or

colMeans(do.call(rbind, dta))
like image 97
akrun Avatar answered Nov 15 '22 03:11

akrun


You can use tapply()

u <- unlist(dta)
tapply(u, names(u), mean)
#      0      1 
# 130.75 172.25 
like image 32
Rich Scriven Avatar answered Nov 15 '22 05:11

Rich Scriven