Anyway of running multiple functions on a single object?

tidyverse

#1

I have a randomly generated sample of numbers. I would like to get the mean and standard deviation from this sample. I would also like to program this in a way where I don’t have to repeat myself. Here is what I could do vs. what I wish I could do. Does anybody know of a function that could do this for me?

set.seed(123)
mean(sample(1:6,10000,replace=T))
sd(sample(1:6,10000,replace=T))

# vs.

set.seed(123)
sample(1:6,10000,replace=T) %>%
  summarise(mean = mean(), sd = sd())

#2

purrr::invoke_map_dbl(list(sd,mean),x=sample(1:6,10000,replace=T))


#3

Perfect, thank you. I was trying invoke_map didn’t think to use invoke_map_dbl


#4

Just assign the sample to a variable.

set.seed(123)
my_sample <- sample(1:6, 10000, replace = TRUE)
list(mean = mean(my_sample), sd = sd(my_sample))

#5

I want to share another option simply because I like so much that it is possible. I do think invoke_map_dbl is a great solution.

Since you can also store functions in a list you don’t have to ‘invoke’.

f <- list(mean, sd)
purrr::map(f, ~ .(sample(1:6,10000,replace=T)))

Which equals in base R

lapply(f, function(fun) fun(sample(1:6,10000,replace=T)))