Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr to iterate over all columns for quantile

Tags:

r

dplyr

I have following R data frame:

           x        y        z
1 -0.5242428 598.7092 1099.503
2 -0.4303593 599.2725 1100.970
3  0.1151290 599.9294 1100.062
4  0.5442775 600.9277 1098.690
5  1.4880749 599.9780 1098.479
6  0.2283675 600.3660 1099.128

I want to get quantiles for each column and thought dplyr is the elegant solution. Following route need each column to be specify but this is not elegant.

> df %>% summarise(`25%`=quantile(x, probs=0.25),
+                  `50%`=quantile(x, probs=0.5),
+                  `75%`=quantile(x, probs=0.75))

I was also trying to see if its possible to use fallowing:

df %>% mutate(quantile(., probs = c(0, 0.25, 0.5, 0.75, 1)))

I assumed that using . would tell the function to do it for all columns but I get the error.

Error: undefined columns selected

Whats the best solution to get

var        25%       50%       75%
x    -0.587382 0.1546231 0.9864742
y     599.2584 599.9998 600.6679
z      1099.31 1100.028 1100.704
like image 741
add-semi-colons Avatar asked Mar 10 '23 09:03

add-semi-colons


1 Answers

We can try

library(tidyverse)
df %>%
    summarise_all(funs(list(quantile(., probs = c(0.25, 0.5, 0.75))))) %>%
    unnest %>%
    transpose %>%
    setNames(., c('25%', '50%', '75%')) %>%
    map_df(unlist) %>%
    bind_cols(data.frame(vars = names(df)), .)
like image 103
akrun Avatar answered Mar 11 '23 23:03

akrun