【问题标题】:How to use dplyr's summarize(across( )) when the function returns a list and the data is groupeddplyr的summary(across())在函数返回列表,数据分组时如何使用
【发布时间】:2020-11-19 23:54:22
【问题描述】:

我正在尝试将 dplyr 的 summarise(across()) 与 MannKendall 函数一起使用(返回一个列表)。如果我不使用 group_by() ,使用它没有问题,但是当我使用它时会出现错误。这是我的代码:

Preds %>% group_by(Municipality) %>% 
   summarise(across(where(is.numeric),~list(MannKendall(.) %>%tidy %>% select(p.value, statistic)))) %>%
   pivot_longer(everything()) %>%
   unnest(c(value))

错误:无法组合 MunicipalityYield 。 产量是我的变量之一,它是数字 这可行,但不是我需要的:

Preds %>%  
   summarise(across(where(is.numeric),~list(MannKendall(.) %>%tidy %>% select(p.value, statistic)))) %>%
   pivot_longer(everything()) %>%
   unnest(c(value))

举个可重现的例子

iris %>%
   group_by(Species) %>%
   summarise(across(starts_with("Sepal"), ~list(MannKendall(.) %>%tidy %>% select(p.value, statistic)))) %>%
   pivot_longer(everything()) %>%
   unnest(c(value)) 

我认为问题在于尝试整理每列中包含列表的结果数据框

【问题讨论】:

  • 请展示一个可重现的小例子
  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • 谢谢!我意识到问题出在整洁的部分。这有效 Preds %>% group_by(Municipality) %>% summarise(across(where(is.numeric),~list(MannKendall(.))) 所以这只是“整理”结果数据帧的问题,其中所有列包含列表。

标签: r dplyr


【解决方案1】:

你可以使用unnest_longer():

library(tidyverse)
library(broom)
library(Kendall)

iris %>%
  group_by(Species) %>%
  summarise(across(starts_with("Sepal"), ~list(
    MannKendall(.) %>% 
      tidy %>% 
      select(p.value, statistic)))) %>%
  unnest_longer(Sepal.Length) %>%
  unnest_longer(Sepal.Width)

# A tibble: 3 x 3
  Species    Sepal.Length$p.value $statistic Sepal.Width$p.value $statistic
  <fct>                     <dbl>      <dbl>               <dbl>      <dbl>
1 setosa                   0.926     -0.0102               0.920    -0.0111
2 versicolor               0.0753    -0.178                0.400    -0.0859
3 virginica                0.750     -0.0326               0.226     0.124 

【讨论】:

  • 谢谢!这就是我需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多