【发布时间】:2021-09-02 11:42:48
【问题描述】:
我正在尝试修改数据表dt 中的newCol 列,仅针对g1 和g2 组中最小的year。
这是一个最小的例子。如您所见,我成功地做了我想做的事,但我想知道是否有更优雅或“数据表”的方式来做到这一点。如果可能,我只希望以 data.table 格式回答!
library(data.table)
# Dummy data
dt = data.table(year = c(2000, 2001, 2003, 2001, 2005, 2000, 2008),
g1 = c(1, 1, 1, 2, 2, 3, 3), g2 = c(88, 88, 88, 88, 88, 54, 54))
# Set up new col to foo
dt[, newCol := "foo"]
# Correct the value for the minimal year, by group g1 and g2
dt[dt[, .I[which.min(year)], by = .(g1, g2)][, V1], newCol := "bar"]
【问题讨论】:
-
您是否同意使用
dplyr包或仅使用data.table包的解决方案? -
对不起,我应该更明确一点:我更喜欢留在 data.table 世界。 (编辑问题)
-
明白了。感谢您的澄清!
标签: r group-by data.table subset