R 将分位数结果转换为列名
我有一个数据集,看起来像这样:R 将分位数结果转换为列名,r,R,我有一个数据集,看起来像这样: df <- structure(list(location_id = c(7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7452, 7452, 7452, 7452, 7452, 7452, 7452, 7452, 7452
df <- structure(list(location_id = c(7451, 7451, 7451, 7451, 7451,
7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7452, 7452, 7452,
7452, 7452, 7452, 7452, 7452, 7452, 7452, 7452, 7452), score = c(55.34,
14.9, 35.13, 6.65, 35.34, 5.86, 7.1, 42.84, 36.57, 6.51, 67.87,
30.75, 52.29, 39.02, 37.58, 35.45, 11.22, 6.68, 9.77, 20.15,
18.61, 32.96, 54.31, 23.79, 9.45)), row.names = c(NA, 25L), class = "data.frame")
+-------------+------+-------+-------+-------+-------+
| location_id | 0% | 25% | 50% | 75% | 100% |
+-------------+------+-------+-------+-------+-------+
| 7451 | 5.86 | 7.1 | 35.13 | 42.84 | 67.87 |
| 7452 | 6.68 | 10.86 | 21.97 | 35.98 | 54.31 |
+-------------+------+-------+-------+-------+-------+
但我要做的是将分位数转换成列名,按location\u id
分组。因此,最终输出将如下所示:
df <- structure(list(location_id = c(7451, 7451, 7451, 7451, 7451,
7451, 7451, 7451, 7451, 7451, 7451, 7451, 7451, 7452, 7452, 7452,
7452, 7452, 7452, 7452, 7452, 7452, 7452, 7452, 7452), score = c(55.34,
14.9, 35.13, 6.65, 35.34, 5.86, 7.1, 42.84, 36.57, 6.51, 67.87,
30.75, 52.29, 39.02, 37.58, 35.45, 11.22, 6.68, 9.77, 20.15,
18.61, 32.96, 54.31, 23.79, 9.45)), row.names = c(NA, 25L), class = "data.frame")
+-------------+------+-------+-------+-------+-------+
| location_id | 0% | 25% | 50% | 75% | 100% |
+-------------+------+-------+-------+-------+-------+
| 7451 | 5.86 | 7.1 | 35.13 | 42.84 | 67.87 |
| 7452 | 6.68 | 10.86 | 21.97 | 35.98 | 54.31 |
+-------------+------+-------+-------+-------+-------+
我们可以在
摘要
之后使用unnest\u-wide
,将其放入列表
列中
library(dplyr)
library(tidyr)
df %>%
group_by(location_id) %>%
summarise(out = list(quantile(score))) %>%
unnest_wider(c(out))
# A tibble: 2 x 6
# location_id `0%` `25%` `50%` `75%` `100%`
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 7451 5.86 7.1 35.1 42.8 67.9
#2 7452 6.68 10.9 22.0 36.0 54.3
完美的我也试过类似的方法,但对我来说并不合适。