2016-11-18 92 views
0

我想处理清单列表。具体而言,我想通过分组变量(每个列表的第一个成员)提取每个列表的第三个成员的数据框,然后使用诸如mean(),median(),sd(),length()等几个函数该组中的数据。输出然后在数据帧返回,看起来像:按组处理列表清单

Grp mean sd ... 
a 5.26 ... ... 
b 6.25 ... ... 

#fake data 
test<-list(
     #member 1=grouping var, 2=identity, 3=dataframe 
     list("a", 54, data.frame(x=c(1,2) ,y=c(3,4))), 
     list("b", 55, data.frame(x=c(5,6) ,y=c(7,8))), 
     list("a", 56, data.frame(x=c(9 ,10),y=c(11,12))), 
     list("b", 57, data.frame(x=c(13,14),y=c(15,NA))) 
     ) 

#what I thought could work but kicks out a strange error 

test2 <-ldply(test, .fun=unlist) 
#note limited to just mean for now 
tapply(test, factor(test$V1), FUN=function(x){mean(as.numeric(x[3:6]), na.rm=TRUE)}, simplify=TRUE) 

所以我的问题是:1。 为什么没有上述工作? 2.这感觉非常笨重,有没有更有效的方法来做到这一点?

+0

什么是你想要的结果吗? – alistaire

+1

你想要完成的事情有点不清楚,但可能像'library(tidyverse); test%>%map_df(〜mutate(.x [[3]],grp = .x [[1]]))%>%group_by(grp)%>%summarise_all(mean,na.rm = TRUE)' – alistaire

+0

编辑来解决你的问题输出。 – TBP

回答

3

在基础R,你可以这样做:

df_list <- tapply(test, 
        sapply(test, `[[`,1), 
        FUN=function(x) do.call(rbind,lapply(x, `[[`,3))) 
t(sapply(df_list, function(x){ 
    list("mean"=mean(unlist(x), na.rm = T), 
     "sd"=sd(unlist(x), na.rm = T), 
     "median"=median(unlist(x), na.rm = T))})) 

    mean  sd  median 
a 6.5  4.440077 6.5 
b 9.714286 4.151879 8 
+0

这样做。谢谢! – TBP