我有一份子列表。每个子列表包含一个相同的数据帧(除了其中的数据相同)和“是/否”标签。如果yes / no标签为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)
我想要一个矢量化函数,它将返回数据帧的行方式平均值,但仅限于$useMe==TRUE
,如下所示:
> desiredFun(main)
id data
1 a 1
2 b 2
3 c 3
答案 0 :(得分: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))