繁体   English   中英

R数据表中连续变量的动态编码

[英]Dynamic encoding of continuous variables in R data.table

我有一个带有两个变量start和end的data.table DT,我想使用动态矢量对其进行编码。 start和end都是某种连续或有序变量(在此示例中,为便于使用,为整数)。 动态向量在开始和结束空间中包含一个动态选择的数据点。 我想基于向量对data.table进行编码。

> DT <- data.table(cust = c('A', 'A', 'B', 'C')
                 , start = c(1,6,2,2)
                 , end = c(4,8,5,10))
> DT
   cust start end
1:    A     1   4
2:    A     6   8
3:    B     2   5
4:    C     2  10

> dynamic_vector <- c(2,5,7,11)

每个添加的列均基于动态矢量的元素。 如果start <= dynamic_vector [i]和dynamic_vector [i] <= end,则列start_dynamic_vector [i]的值为1。

我可以使用for循环来做到这一点:

> for (i in dynamic_vector) DT[, (paste0('month_', i)) := (i >= start & end >= i) + 0L]
> DT
   cust start end month_2 month_5 month_7 month_11
1:    A     1   4       1       0       0        0
2:    A     6   8       0       0       1        0
3:    B     2   5       1       1       0        0
4:    C     2  10       1       1       1        0

我如何在不使用for循环的情况下做到这一点? 我正在处理两个连续变量start和end。 动态矢量可能会很大(几百个元素)。 DT也是一个相对较大的表(约5000万个条目)。 for循环需要很长时间!

使用%between%Map ,然后一次分配:=所有输出变量:

DT[
  ,
  paste0("month_", dynamic_vector) := lapply(
    Map(`%between%`, dynamic_vector, .(.(start,end))), as.integer
  )
]

#   cust start end month_2 month_5 month_7 month_11
#1:    A     1   4       1       0       0        0
#2:    A     6   8       0       0       1        0
#3:    B     2   5       1       1       0        0
#4:    C     2  10       1       1       1        0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM