【问题标题】:list column group by and summarise列出列分组并总结
【发布时间】:2019-01-18 10:33:34
【问题描述】:

目标:我想编写以下代码,它可以在数据帧上正常工作,但对于列表列工作流程的每个数据帧。

请注意,我采用列表的第一个元素并创建了一个数据框,然后使用该数据框,因为我还没有弄清楚如何group_by 嵌套列表(请参阅已尝试)。

DATA

当前工作:

nested_NBA <- NBA%>%
  group_by(season)%>%
  nest()
 
one_season <- nested_NBA$data[1]

one_season%>% 
  bind_rows()%>%
  group_by(player)%>%
  summarise(shots_attempts_ratio=sum(shot_made)/n(),
            total_attempts=n(),
            shots=sum(shot_made))

已经尝试过:

nested_NBA%>% map(data, ~group_by(.x$player))

错误:

Warning messages:
1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
2: In .f(.x[[i]], ...) : data set ‘~group_by(.x$player)’ not found
3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
4: In .f(.x[[i]], ...) : data set ‘~group_by(.x$player)’ not found

【问题讨论】:

    标签: r functional-programming purrr


    【解决方案1】:

    nest 步骤之后,我们可以使用mapmutate 中循环“数据”list,然后使用它执行group_bysummarise

    library(tidyverse)
    NBA%>%
      group_by(season)%>%
      nest() %>%
      mutate(data = map(data, ~ .x %>%
            group_by(player)%>%
            summarise(shots_attempts_ratio=sum(shot_made)/n(),
            total_attempts=n(),
            shots=sum(shot_made))
            )) %>%
     unnest
    

    【讨论】:

    • @delcast 是的,你很接近。问题在于提取列值而不是在 group_by 中指定列的标识符
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多