r - tidyverse 中的条件 ntile

标签 r dplyr tidyverse quantile

我想使用 tidyverse 仅使用行的子集来计算 ntiles。以下基本 R 代码可以满足我的需求:

基础R:

diamonds$conditional_quartiles_var                           <- NA
diamonds$conditional_quartiles_var[ diamonds$price >= 1000 ] <- ntile( diamonds$price[ diamonds$price >= 1000 ], n = 4 )
diamonds$conditional_quartiles_var[ diamonds$price <  1000 ] <- "Less than 1000"

diamonds %>% count(conditional_quartiles_var)

输出(我想要的):

# A tibble: 5 x 2
  conditional_quartiles_var     n
                      <chr> <int>
1                         1  9861
2                         2  9860
3                         3  9860
4                         4  9860
5            Less than 1000 14499

上面的结果是我想要的,因为 ntiles 仅根据价格 >= 1000 的值计算。

Tidyverse 尝试

我的 tidyverse 实现失败,因为 ntile 是根据整个价格向量计算的:

library(tidyverse)


diamonds %>% 
    mutate( wrong_conditional_quartiles_var = case_when(  price >= 1000 ~   ntile(price, n = 4) %>% as.character(),
                                                          price <  1000 ~   "Less than 1000")) %>%
    count( wrong_conditional_quartiles_var)

输出(不是我想要的):

# A tibble: 4 x 2
  wrong_conditional_quartiles_var     n
                            <chr> <int>
1                               2 12471
2                               3 13485
3                               4 13485
4                  Less than 1000 14499

最佳答案

我们可以使用替换

library(dplyr)
diamonds %>%
   mutate(quart = "Less than 1000", 
          quart = replace(quart, price >= 1000, ntile(price[price>=1000], 4))) %>%
   count(quart)
# A tibble: 5 x 2
#           quart     n
#           <chr> <int>
#1              1  9861
#2              2  9860
#3              3  9860
#4              4  9860
#5 Less than 1000 14499

关于r - tidyverse 中的条件 ntile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032583/

相关文章:

r - 识别另一个列表中包含的列表元素,这些元素都是数据框的元素

r - 计算 r 中值组合的出现次数

r - 如何更改 R data.frame 中的行名称?

r - 使用 tidyverse 工具展平从关系数据库派生的嵌套列表的最佳方法是什么?

r - dplyr 创建因子水平的聚合百分比

r - Rscript.exe 中包含 Unicode 字符的文件路径

r - R 中 dplyr 中的 "Adding missing grouping variables"消息

通过facet_wrap重新排序ggplot barplot x轴

r - 如何使用R中的并行处理来分析大型时间序列数据集

r - 强制 imap 使用命名向量上的索引