У меня есть фрейм данных, в котором есть строки строк.Я хочу посчитать вхождение слов в строках в зависимости от того, какие слова появляются в столбце.Как я могу добиться этого с помощью кода ниже? Можно ли каким-либо образом изменить приведенный ниже код для достижения этой цели или кто-нибудь может предложить другой фрагмент кода, который не требует циклов ?Большое спасибо заранее!
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