Search code examples
rfunctionmeasure

use function on multiple columns


I've created this function to calculate mean, median and SD:

f1<- function(x) c(mean= round(mean(x),2), median= round(median(x),2), sd= round(sd(x),2))

I want to use it for multiple columns (names of columns: domain 1, domain2, domain3, total)

I want to know how to use the function, and would you recommend a better way than using a function to present mean, median and sd?


Solution

  • You can use sapply to apply f1 function to multiple columns.

    f1<- function(x) c(mean= round(mean(x),2), median= round(median(x),2), sd= round(sd(x),2))
    cols <- c('mpg', 'cyl')
    sapply(mtcars[cols], f1)
    
    #         mpg  cyl
    #mean   20.09 6.19
    #median 19.20 6.00
    #sd      6.03 1.79
    

    Using dplyr :

    mtcars %>%
      summarise(across(c(mpg, cyl), list(mean = mean, sd = sd, median = median)))
    
    #  mpg_mean   mpg_sd mpg_median cyl_mean   cyl_sd cyl_median
    #1 20.09062 6.026948       19.2   6.1875 1.785922          6