1

我有一个子列表。每个子列表包含一个相同的数据框(除了其中的数据外,其他相同)和一个“是/否”标签。如果是/否标签为真,我想找到数据帧的逐行平均值。

#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)

我想要一个矢量化函数,它将返回数据帧的逐行平均值,但前提是$useMe==TRUE,如下所示:

> desiredFun(main)
   id  data
1   a     1
2   b     2
3   c     3
4

1 回答 1

2

这是解决此问题的一种相当通用的方法:

# Extract the "data" portion of each "main" list element
# (using lapply to return a list)
AllData <- lapply(main, "[[", "data")
# Extract the "useMe" portion of each "main" list element
# using sapply to return a vector)
UseMe <- sapply(main, "[[", "useMe")
# Select the "data" list elements where the "useMe" vector elements are TRUE
# and rbind all the data.frames together
Data <- do.call(rbind, AllData[UseMe])
library(plyr)
# Aggregate the resulting data.frame
Avg <- ddply(Data, "id", summarize, data=mean(data))
于 2012-07-27T21:35:03.857 回答