【问题标题】:Converting quantile results into column names将分位数结果转换为列名
【发布时间】:2020-05-16 14:33:21
【问题描述】:

所以我有一个看起来像这样的数据集:

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")

现在,我知道如何获得分位数结果了,这很容易:

quantile(df$score)

但我正在尝试将分位数转换为列名,按location_id 分组。所以最终的输出看起来像这样:

+-------------+------+-------+-------+-------+-------+
| 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 |
+-------------+------+-------+-------+-------+-------+

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以在summarise 之后使用unnest_wider 进入list 列

    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
    

    或使用data.table

    library(data.table)
    setDT(df)[, as.list(quantile(score)), location_id]
    #    location_id   0%     25%   50%     75%  100%
    #1:        7451 5.86  7.1000 35.13 42.8400 67.87
    #2:        7452 6.68 10.8575 21.97 35.9825 54.31
    

    【讨论】:

    • 完美!我曾尝试过类似的方法,但它不适合我。
    猜你喜欢
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多