Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206180

dplyr: Is it possible to return two columns in summarize using one function?

$
0
0

Say I have a function that returns two scalars, and I want to use it with summarize, e.g.

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.

I tried both ways, but can't figure it out.

However, this can be done with data.table

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

Is there a way to do this in dplyr?


Viewing all articles
Browse latest Browse all 206180

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>