gpt4 book ai didi

r - 将 data.table 列中的向量值替换为另一个 data.table 中的相关值的最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-02 02:46:25 26 4
gpt4 key购买 nike

这是我的问题的缩小样本。我有一个 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 开始的连续 ID 数字。

最佳答案

您可以使用match :

library(data.table)

ID.table[, IDs := lapply(IDs,function(x) word.table$word[match(x,word.table$ID)])]
ID.table

# IDs
#1: test,sentence,.
#2: is,a,test

如果您可以使用 tidyverse函数的另一个选择是 unnest IDs并加入 word.table .

library(dplyr)

ID.table %>%
mutate(row = row_number()) %>%
tidyr::unnest(IDs) %>%
left_join(word.table, by = c('IDs' = 'ID')) %>%
group_by(row) %>%
summarise(Ids = list(word)) %>%
select(-row)

关于r - 将 data.table 列中的向量值替换为另一个 data.table 中的相关值的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62735963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com