I have a list of sublists. Each sublist contains an identical data frame (identical except for the data inside it) and a ‘yes/no’ label. I’d like to find the row-wise mean of the data frames, if the yes/no label is TRUE.
#Create the data frames
id <- c("a", "b", "c")
df1 <- data.frame(id=id, data=c(1, 2, 3))
df2 <- df1
df3 <- data.frame(id=id, data=c(1000, 2000, 3000))
#Create the sublists that will store the data frame and the yes/no variable
sub1 <- list(data=df1, useMe=TRUE)
sub2 <- list(data=df2, useMe=TRUE)
sub3 <- list(data=df3, useMe=FALSE)
#Store the sublists in a main list
main <- list(sub1, sub2, sub3)
I want a vectorized function that will return the row-wise average of the data frames, but only if $useMe==TRUE, like so:
> desiredFun(main)
id data
1 a 1
2 b 2
3 c 3
Here’s a fairly general way to approach this problem: