【问题标题】:Assign bin value according to vector of thresholds根据阈值向量分配 bin 值
【发布时间】:2020-11-03 23:26:01
【问题描述】:

我有一个阈值向量,我想用它在 data.table 上创建列的 bin

thrshlds <- seq(from = 0, to = 1, by = 0.05)
test <- data.table(
  A = rnorm(1000, 0.7, 1),
  B = rbinom(1000, 3, 0.6)
)

我要实现的逻辑是:

如果 A 列的值等于或小于每个阈值的值,则为其分配相应的阈值。类似于 SQL case when,但无需手动分配每个阈值。

类似:

test[, new_category := fcase(A <= thrshlds[1], thrshlds[1],
                             A <= thrshlds[2], thrshlds[2],
                             .....)]

但我不知道如何在 data.table 查询中进行这种迭代。

谢谢!

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    你可以使用cut

    library(data.table)
    test[, new_category := cut(A, c(-Inf, thrshlds), thrshlds)]
    test
    
    #                 A B new_category
    #   1:  0.220744413 3         0.25
    #   2: -0.814886795 3            0
    #   3:  1.134536656 2         <NA>
    #   4:  0.180463333 1          0.2
    #   5: -0.134559033 1            0
    #  ---                            
    # 996: -0.332559649 1            0
    # 997:  0.585641110 0          0.6
    # 998:  0.765738832 2          0.8
    # 999:  2.167632026 2         <NA>
    #1000:  0.008935421 2         0.05
    

    【讨论】:

      【解决方案2】:

      不确定这是否是一种合适的方法,但这里有一个滚动连接选项似乎可行:

      test[, new_category := data.table(thrshlds)[test, on="thrshlds==A", x.thrshlds, roll=-Inf] ]
      
      #test[sample(1000, 12)]
      #             A B new_category
      # 1: -1.1317742 3         0.00
      # 2:  0.2926608 2         0.30
      # 3:  1.5441214 2           NA
      # 4:  0.9249706 1         0.95
      # 5:  1.2663975 2           NA
      # 6:  0.6472989 0         0.65
      # 7: -0.5606153 2         0.00
      # 8:  0.4439064 2         0.45
      # 9:  0.8182938 1         0.85
      #10:  0.8461909 2         0.85
      #11:  1.0237554 1           NA
      #12:  0.7752323 1         0.80
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-22
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        • 2020-11-22
        相关资源
        最近更新 更多