首页 > 解决方案 > R:如何检查列表中是否存在多个列的值

问题描述

我有一个数据框,其中的列包含构成 ngram 的单词。我想总结每个 ngram 中停用词的数量并将此列添加到数据框中,但我想不出一种优雅的方法来处理 n 的多个值(4-gram、5-gram 等...... )。

到目前为止,我一直在做以下事情

mutate(Bigram_Counts_By_Company,
   stopword_count = (word1  %in% stop_words$word) %>% as.integer() +
                    (word2 %in% stop_words$word) %>% as.integer())

现在这可行,但我更愿意编写一个通用函数,该函数对所有以“名称”开头的列执行相同的操作。

我想做什么

mutate(Web_Bigram_Counts_By_Company,
   stopword_count = select(Web_Bigram_Counts_By_Company, starts_with("word")) %in% stop_words$word)

select(Web_Bigram_Counts_By_Company, starts_with("word"))非常适合选择名称以“name”开头的列,但是当我在调用 mutate 中使用它时,我得到了这个错误:Column 'stopword_count' must be length 360463 (the number of rows) or one, not 2

这只是一个简单的 R 基础错误还是我要解决这个问题?

标签: rdplyr

解决方案


推荐阅读