2016-11-18 90 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