r - 根据其他列中的现有单词逐行计算字符串中单词的出现次数
问题描述
我有一个包含多行字符串的数据框。我想根据列中出现的单词来计算行中单词的出现次数。如何使用下面的代码实现这一点?可以以某种方式修改下面的代码来实现这一点,或者任何人都可以建议另一段不需要循环的代码吗?提前非常感谢!
df <- data.frame(
words = c("I want want to compare each ",
"column to the values in",
"If any word from the list any",
"replace the word in the respective the word want"),
want= c("want", "want", "want", "want"),
word= c("word", "word", "word", "word"),
any= c("any", "any", "any", "any"))
#add 1 for match and 0 for no match
for (i in 2:ncol(df))
{
for (j in 1:nrow(df))
{
df[j,i] <- ifelse (grepl (df[j,i] , df$words[j]) %in% "TRUE", 1, 0)
}
print(i)
}
*'data.frame': 4 obs. of 4 variables:
$ words: chr "I want want to compare each " "column to the values in " "If any word from the words any" "replace the word in the respective the word"
$ want : chr "want" "want" "want" "want"
$ word : chr "word" "word" "word" "word"
$ any : chr "any" "any" "any" "any"*
输出应如下所示:
words want word any
1 I want want to compare each 2 0 0
2 column to the values in 0 0 0
3 If any word from the list any 0 1 2
4 replace the word in the respective the word want 1 2 0
现有代码的当前输出如下所示:
words want word any
1 I want want to compare each 1 0 0
2 column to the values in 0 0 0
3 If any word from the list any 0 1 1
4 replace the word in the respective the word want 1 1 0
解决方案
使用tidyverse
(使用稍微违反语法$
):
library(tidyverse)
df %>%
mutate_at(vars(-words),function(x) str_count(df$words,x))
words want word any
1 I want want to compare each 2 0 0
2 column to the values in 0 0 0
3 If any word from the list any 0 1 2
4 replace the word in the respective the word want 1 2 0
或者modify_at
按照@Sotos 的建议使用 and ,我们可以使用它.
来维护tidyverse
语法。
df %>%
modify_at(2:ncol(.),function(x) str_count(.$words,x))
words want word any
1 I want want to compare each 2 0 0
2 column to the values in 0 0 0
3 If any word from the list any 0 1 2
4 replace the word in the respective the word want 1 2 0
推荐阅读
- ios - 使用 CoreBluetooth CBL2CAPChannel 移动数据
- java - 如何单击具有输入类型和值的按钮?
- jquery - 如何使用jQuery ajax 重新加载用户不知道的页面是正在重新加载的页面?
- html - CSS样式表第一次没有链接到HTML web-dev
- android - 使用改造(pdf,ppt,png,jpg)“code = 500,内部服务器错误”上传文件有什么问题
- android - 如何绑定具有多个 IN 值的 SQL 语句?
- android - 如何使用导航视图
- c# - Net Core:用于数据检查的私有成员和数据注释之间的区别
- razorpay - 如何通过razorpay api取消特定用户(最终用户)的订阅
- python - TypeError: center() 最多接受 2 个参数(给定 4 个)