【问题标题】:How to assign deciles in a grouped data using dplyr?如何使用 dplyr 在分组数据中分配十分位数?
【发布时间】:2020-08-26 14:03:10
【问题描述】:

我有以下数据框,其中包含大约 1700 个县的数据:

# A tibble: 47,898 x 3
# Groups:   countyfips [1,774]
   countyfips day_month_year case_rate
        <int> <date>             <dbl>
 1       1001 2020-01-12             0
 2       1001 2020-01-19             0
 3       1001 2020-01-26             0
 4       1001 2020-02-02             0
 5       1001 2020-02-09             0
 6       1001 2020-02-16             0
 7       1001 2020-02-23             0
 8       1001 2020-03-01             0
 9       1001 2020-03-08             0
10       1001 2020-03-15             0
# … with 47,888 more rows 

我想按日期对它们进行分组,然后根据给定时间的病例率将它们分配到四分位数(同时将它们与其他县进行比较)。

我已经尝试了代码:

Affinity_County_Weekly.csv %>% group_by(day_month_year) %>% mutate(case_rate_decile = ntile(data = case_rate, 10, na.rm = TRUE))

但这会返回以下错误:

错误:mutate() 输入 case_rate_decile 有问题。 x 未使用的参数(数据 = case_rate,na.rm = TRUE) ℹ 输入case_rate_decilentile(data = case_rate, 10, na.rm = TRUE)。 ℹ 第1组出现错误:day_month_year = 2020-01-12。 运行rlang::last_error() 看看哪里出错了。

如何使用 dplyr 函数做到这一点?

【问题讨论】:

  • 你要计算case_rate属于哪个分位数,得到十个分位数?

标签: r dataframe dplyr


【解决方案1】:

我认为这里的问题是您使用显式参数 datana.rm 表示 ntile;这些不是形式参数。 ntile 接受 xn

Affinity_County_Weekly.csv %>%
  group_by(day_month_year) %>%
  mutate(case_rate_decile = ntile(x = case_rate, 10))

应该可以解决问题。如果 case_rate 中存在 NA,那么出于计算分位数的目的,它们将被忽略,但会保留在输出数据中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2021-09-27
    相关资源
    最近更新 更多