在 data.table 列分配中使用先前定义的列

Use a previously defined column in data.table column assignment

假设我有一个 data.table,其中包含有关 收入工作时间id个人。
我想计算每小时的收入 iph,然后计算每个人的收入随时间的变化 (iphd)。

在最后的data.table中我想存储两个变量iphiphd

data <- data.table(
  income = c(100, 120, 140, 205, 200, 220),
  hours =  c( 10,  11,  12,  18,  17,  21),
  id =     c(  1,   1,   1,   2,   2,   2)
)

(data
  [, iph := income / hours]
  [, iphd := c(NA, diff(iph)), by = id])[]

用于基础 R 的 within 函数,我想在同一个表达式中定义它之后立即访问 iph。类似于:

# Trial no. 1
data[,
     `:=`(
       iph := income / hours,
       iphd := c(NA, diff(iph))),
     by = id][]

# Trial no. 2
data[, `:=`({
  iph = income / hours
  iphd = c(NA, diff(iph))
}), by = id][]

# Trial no. 3
data[, .({
  iph = income / hours
  iphd = c(NA, diff(iph))
}), by = id][]

但是,none 这些解决方案有效。
除了我上面建议的两步法之外,还有其他方法吗?

计算 {...} 和 return 之间的结果列表

data[, c("iph", "iphd") := {
  iph <- income / hours
  iphd <- c(NA, diff(iph))
  list(iph,iphd)
}, by = id]

#    income hours id      iph       iphd
# 1:    100    10  1 10.00000         NA
# 2:    120    11  1 10.90909  0.9090909
# 3:    140    12  1 11.66667  0.7575758
# 4:    205    18  2 11.38889         NA
# 5:    200    17  2 11.76471  0.3758170
# 6:    220    21  2 10.47619 -1.2885154

没有花括号:

data[, c("iph", "iphd") := list(income / hours, 
                                c(NA, diff(income / hours))), by = id][]