Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a function to get summary statistics as columns?

I have three workflows to get Mean, Standard Deviation, and Variance. Would it be possible to simplify this by creating one function with one table with all the summaries as the result?

Mean

iris %>% 
  select(-Species) %>% 
  summarise_all( , mean, na.rm = TRUE) %>% 
  t() %>% 
  as.data.frame() %>% 
  rownames_to_column("Name") %>% 
  rename(Mean = V1)

Standard Deviation

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

iris %>% 
  select(-Species) %>% 
  summarise_all(., sd, na.rm = TRUE) %>% 
  t() %>% 
  as.data.frame() %>% 
  rownames_to_column("Name") %>% 
  rename(SD = V1)

Variance

iris %>% 
  select(-Species) %>% 
  summarise_all(., var, na.rm = TRUE) %>% 
  t() %>% 
  as.data.frame() %>% 
  rownames_to_column("Name") %>% 
  rename(Variance = V1)

>Solution :

We could reshape to ‘long’ format and then do a group by operation to create the three summarise columns

library(dplyr)
library(tidyr)
iris %>% 
   select(where(is.numeric)) %>% 
   pivot_longer(cols = everything(), names_to = "Name") %>% 
   group_by(Name) %>% 
   summarise(Mean = mean(value, na.rm = TRUE),
            SD = sd(value, na.rm = TRUE), 
            Variance = var(value, na.rm = TRUE))

-output

# A tibble: 4 × 4
  Name          Mean    SD Variance
  <chr>        <dbl> <dbl>    <dbl>
1 Petal.Length  3.76 1.77     3.12 
2 Petal.Width   1.20 0.762    0.581
3 Sepal.Length  5.84 0.828    0.686
4 Sepal.Width   3.06 0.436    0.190
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading