dplyr遍历所有列以获得分位数 [英] dplyr to iterate over all columns for quantile

查看:55
本文介绍了dplyr遍历所有列以获得分位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下R数据帧:

           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

我想获得每一列的分位数,并认为 dplyr 是一个优雅的解决方案。遵循路线需要指定每列,但这不是很优雅。

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.

错误:未定义的列已选中

什么最佳解决方案

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


推荐答案

我们可以尝试

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)), .)

这篇关于dplyr遍历所有列以获得分位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆