【发布时间】:2020-07-05 01:21:51
【问题描述】:
这是我的问题的缩小示例。我有一个 data.table,其中有一列以矢量形式存在的多个 ID。这些 ID 都对应另一个 data.table 中的单词。
ID.table <- data.table(IDs = list(c(4, 5, 6), c(2, 3, 4)))
word.table <- data.table(ID = c(1, 2, 3, 4, 5, 6), word = c("This", "is", "a", "test", "sentence", "."))
产生
IDs
1: 4,5,6
2: 2,3,4
和
ID word
1: 1 This
2: 2 is
3: 3 a
4: 4 test
5: 5 sentence
6: 6 .
我需要将 ID.table 中的所有 ID 转换为 word.table 中对应的单词,如下所示。
IDs
1: test,sentence,.
2: is,a,test
我知道我可以使用 for 循环并遍历 ID.table 中的每个向量来做到这一点,但我的实际表有数千行,这意味着它运行非常缓慢。
row <- 1
for(ID.row in ID.table[, IDs]){
word.row <- word.table[ID %in% ID.row]$word
ID.table[row] <- word.row
row <- row + 1
}
有没有更有效的方法来做到这一点?
编辑:我在 word.table 中列出从 1 开始的顺序 ID 是一个错误。 ID.table 和 word.table 看起来更像这样。
IDs
1: 608,609,610
2: 606,607,608
和
ID word
1: 605 This
2: 606 is
3: 607 a
4: 608 test
5: 609 sentence
6: 610 .
其中 ID.table 的每一行将是一个不从 1 开始的序列号向量,并且 word.table 的 ID 列将具有不总是不从 1 开始的序列号。
【问题讨论】:
标签: r data.table tidyverse