【发布时间】:2018-05-24 04:37:01
【问题描述】:
我有一个data.table DT_words(大维度):
DT_words <- data.table(word = c('word1', 'word2', 'word3','word4'))
我有另一个 data.table DT_strings 包含一个包含大量字符串的列
DT_strings <- data.table(string = c('string1 made of word1', 'string2 made of word2 and word2 and word3 and word1ly', 'string3 made of word1 and word2'))
对于 DT_word 中的每个单词,我想计算 DT_string 中所有字符串的出现总数,并将该值保存为 DT_word 中的列。 我正在使用 for 循环,它看起来很丑。
我尝试使用 lapply 和 mapply 但无济于事,因为该函数需要内部输入。
这里是 for-loop that words(但它需要很长时间而且很丑)
require(stringr)
for (i in 1:nrow(DT_words))
{
DT_words$word_count[i] <- sum(str_count(DT_strings$string,
paste0(c("\\b("),paste(DT_words[i, .(word)]),c(")\\b"))))
}
我知道格式更像是 data.frame,但由于我使用的是循环,所以这并不重要,不是吗? 无论如何,我想知道我是否可以在 data.table 中使用 apply 并摆脱这种丑陋。
期望的输出是:
> DT_words
word word_count
1: word1 2
2: word2 3
3: word3 1
4: word4 0
编辑:我编辑了 DT_strings 以包含更多单词匹配的示例。我只对匹配整个单词感兴趣,因此必须以某种方式包含正则表达式语法。
【问题讨论】:
标签: r regex dynamic nested data.table