B. Davis
B. Davis

Reputation: 3441

Trying to generate averages across multiple lists

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.

Upvotes: 7

Views: 371

Answers (5)

Rich Scriven
Rich Scriven

Reputation: 99331

You can use tapply()

u <- unlist(dta)
tapply(u, names(u), mean)
#      0      1 
# 130.75 172.25 

Upvotes: 5

David Arenburg
David Arenburg

Reputation: 92282

Here's approach using Reduce

Reduce(`+`, dta)/length(dta)
#      0      1 
# 130.75 172.25 

Upvotes: 4

talat
talat

Reputation: 70256

colMeans(matrix(unlist(dta), ncol = 2, byrow = TRUE))
#[1] 130.75 172.25

or with dplyr & reshape2:

library(reshape2); library(dplyr)
melt(dta) %>% group_by(Var1) %>% summarise(mean = mean(value))
#Source: local data frame [2 x 2]
#
#  Var1   mean
#1    0 130.75
#2    1 172.25

Upvotes: 3

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

Another approach:

sapply(split(unlist(dta), 0:1), mean)
#      0      1 
# 130.75 172.25 

Upvotes: 3

akrun
akrun

Reputation: 886948

You could try

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

Or

colMeans(do.call(rbind, dta))

Upvotes: 5

Related Questions