2012-07-27 94 views
1

我有一个列表子列表。每个子列表都包含一个相同的数据框(除了其中的数据外)和“是/否”标签。如果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

当你说“相同”时,你的意思是'id'对data.frame中的每一行都是一样的,只有'data'列的值有所不同? – 2012-07-27 21:20:36

+0

是的,这是正确的。真的每个子列表可能应该是一个对象,但我还没有深入研究R中的OOP。 – 2012-07-27 23:14:07

回答

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)) 
+0

你能解释为什么lapply(x,“[[”...语法有效吗?我不会猜到它会这样,因为“[[”并不是我所知道的函数) – 2012-07-27 23:17:55

+1

哦,但它是。你可以像任何其他的一样使用它,例如'x <-list(a = 1:3,b = letters,c = LETTERS)',你可以用'x [[“b”]]'来获得小写字母元素,或等价地:''[[“(x,”b“)'.R中的所有内容都是一个函数 – 2012-07-28 02:19:18

+0

很酷!谢谢。 – 2012-07-28 14:43:57