gpt4 book ai didi

r - 根据其他列中的现有单词,按行计算字符串中单词的出现次数

转载 作者:行者123 更新时间:2023-12-05 00:10:47 25 4
gpt4 key购买 nike

我有一个包含多行字符串的数据框。我想根据列中出现的单词来计算行中单词的出现次数。我怎样才能用下面的代码实现这一点? 是否可以修改以下代码以实现此目的,或者任何人都可以建议另一段不需要循环的代码 ?非常感谢!

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 的建议,我们可以使用 .维护 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

关于r - 根据其他列中的现有单词,按行计算字符串中单词的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56543866/

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