【问题标题】:Convert values to keys based on a key table with dplyr and R [duplicate]基于使用 dplyr 和 R 的键表将值转换为键 [重复]
【发布时间】:2018-07-27 18:40:36
【问题描述】:

在下文中,data1 是一个主数据库。 data2 是将分数映射到级别的函数。我想为 data1 分配级别。

data1 <- data_frame(id=1:6,score=1:6-0.1)
data2 <- data_frame(score=2:4,level=c("a","b","c"))

最终输出:

 id score level

 1   0.9 a    
 2   1.9 a    
 3   2.9 b    
 4   3.9 c    
 5   4.9 c    
 6   5.9 c   

基本上,

if score < data2$score[1], level = data2$score[1]. 
if score > data2$score[length(data2$score)], level = data2$score[length(data2$score)].
if data2$score[i] < score < data2$score[i+1], level = data2$level[i]

有没有办法用 dplyr(最好)或 base R 来实现这一点?我知道 data.table 可能有办法做到这一点,但我也想寻求其他一些选择

【问题讨论】:

  • 为什么最后输出的第4行是a b?
  • @Gregor 错字。对不起

标签: r dplyr


【解决方案1】:

使用cut 对数据进行分箱:

data1$result = cut(data1$score, breaks = c(-Inf, data2$score[-nrow(data2)], Inf), labels = data2$level)
data1
# # A tibble: 6 x 3
#      id score result
#   <int> <dbl> <fct> 
# 1     1   0.9 a     
# 2     2   1.9 a     
# 3     3   2.9 b     
# 4     4   3.9 c     
# 5     5   4.9 c     
# 6     6   5.9 c   

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多