1

サブリストのリストがあります。各サブリストには、同一のデータ フレーム (内部のデータを除いて同一) と「はい/いいえ」ラベルが含まれています。はい/いいえラベルが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
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 に答える