library(data.table)
#> Warning: package 'data.table' was built under R version 3.5.3
test_db <-
data.table(
Name = c("A", "B", "C", "D", "E", "F"),
ID = c(1, 1, 1, 2, 2, 2),
Date = c("2019 Q3", "2019 Q2", "2019 Q1", "2019 Q3", "2019 Q2", "2019 Q1")
)
test_db
#> Name ID Date
#> 1: A 1 2019 Q3
#> 2: B 1 2019 Q2
#> 3: C 1 2019 Q1
#> 4: D 2 2019 Q3
#> 5: E 2 2019 Q2
#> 6: F 2 2019 Q1
setorder(test_db,-"Date")
perID_list <- split(test_db,by="ID")
for (i in 1:length(perID_list)) {
perID_list[[i]][,"Name":=perID_list[[i]]$Name[1]]
}
result_db <- rbindlist(perID_list)
result_db
#> Name ID Date
#> 1: A 1 2019 Q3
#> 2: A 1 2019 Q2
#> 3: A 1 2019 Q1
#> 4: D 2 2019 Q3
#> 5: D 2 2019 Q2
#> 6: D 2 2019 Q1
Created on 2019-07-24 by the reprex package (v0.3.0)
我有一个这样的数据表。我想更新名称列,以确保旧名称与新名称一致(最新日期为2019 Q3)
我想通过将data.table分成列表组然后一个接一个地循环来做到这一点。有一个更好的方法吗?由于我的桌子很大...