【问题标题】:Processing lists of lists by group按组处理列表列表
【发布时间】:2016-11-18 22:18:16
【问题描述】:

我想处理一个列表列表。具体来说,我想通过分组变量(每个列表的第一个成员)提取每个列表的第三个成员的数据框,然后使用 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. 感觉很笨重,有没有更高效的方法?

【问题讨论】:

  • 你想要的结果是什么?
  • 您要完成的工作有些不清楚,但可能类似于 library(tidyverse) ; test %&gt;% map_df(~mutate(.x[[3]], grp = .x[[1]])) %&gt;% group_by(grp) %&gt;% summarise_all(mean, na.rm = TRUE)
  • 已编辑以解决您的问题重新输出。
  • 那么在获取mean/sd/etc 时,您是否将xy 值混为一谈?
  • 是的,它们是集总的

标签: r plyr tapply split-apply-combine


【解决方案1】:

在基础 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   

【讨论】:

  • 就可以了。谢谢!
猜你喜欢
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 2010-09-14
  • 2023-04-06
  • 1970-01-01
相关资源
最近更新 更多