r语言 - dplyr:是否可以使用一个函数在汇总中返回两列?



>假设我有一个返回两个标量的函数,我想将其与summarize一起使用,例如

fn = function(x) {
list(mean(x), sd(x))
}
iris %>%
summarize(fn(Petal.Length)) # Error: Column `fn(Petal.Length)` must be length 1 (a summary value), not 2

iris %>% 
summarize(c("a","b") := fn(Petal.Length)) 
# Error: The LHS of `:=` must be a string or a symbol Run `rlang::last_error()` to see where the error occurred.

我尝试了两种方法,但无法弄清楚。

但是,这可以通过data.table来完成

library(data.table)
iris1 = copy(iris)
setDT(iris1)[, fn(Petal.Length)]

有没有办法在dplyr做到这一点?

是的,您可以将它们另存为列中的列表,然后使用unnest_wider将它们分隔在不同的列中。

fn = function(x) {
list(mean = mean(x),sd = sd(x))
}
library(dplyr)
library(tidyr)
iris %>%
summarise(temp = list(fn(Petal.Length))) %>% 
unnest_wider(temp)
# A tibble: 1 x 2
#   mean    sd
#  <dbl> <dbl>
#1  3.76  1.77

或者unnest_longer将它们放在单独的行中

iris %>%
summarise(temp = list(fn(Petal.Length))) %>% 
unnest_longer(temp)
#   temp temp_id
#  <dbl> <chr>  
#1  3.76 mean   
#2  1.77 sd     

最新更新