I want to calculate multiple functions from a vector in an efficient way but I couldn't figure out how.
I tried with pipes but it only works for the first variable, and adding a ,
doesn't work.
vec1 %>%
sd(),
mean()
I guess I could always transform it into a dataframe and use summarize, but I rather not do that.
Thank you,
CodePudding user response:
x <- 1:10
c(sum(x), mean(x), sd(x))
#> [1] 55.00000 5.50000 3.02765
library(magrittr)
x %>%
{c(sum(.), mean(.), sd(.))}
#> [1] 55.00000 5.50000 3.02765
x %>%
sapply(c(sum, mean, sd), rlang::exec, .)
#> [1] 55.00000 5.50000 3.02765
Created on 2021-11-26 by the reprex package (v2.0.1)
CodePudding user response:
You may try
library(dplyr)
x <- c(1:10)
func <- function(x){
c(mean(x), sd(x))
}
x %>%
func
[1] 5.50000 3.02765
CodePudding user response:
Return the output in a list.
calculate_stats <- function(x) {
list(mean = mean(x), sd = sd(x), sum = sum(x))
}
result <- calculate_stats(1:10)
result
#$mean
#[1] 5.5
#$sd
#[1] 3.02765
#$sum
#[1] 55
Separate values can be extracted from the result
using $
.
result$mean
#[1] 5.5
result$sd
#[1] 3.02765