我想在favor
数据中提取与target
匹配的dictionary
列的特定字符串。这是我的数据:
dictionary <- c("apple", "banana", "orange", "grape")
target <- data.frame("user" = c("A", "B", "C"),
"favor" = c("I like apple and banana", "grape and kiwi", "orange, banana and grape are the best"))
target
user favor
1 A I like apple and banana
2 B grape and kiwi
3 C orange, banana and grape are the best
以下是我的预期结果result
。我想基于我在字典中匹配的最喜欢的内容(在我的例子中, 3 )自动创建列,并提取我在字典中匹配的字符串。
result <- data.frame("user" = c("A", "B", "C"),
"favor_1" = c("apple", "grape", "orange"),
"favor_2" = c("banana", "", "banana"),
"favor_3" = c("", "", "grape"))
result
user favor_1 favor_2 favor_3
1 A apple banana
2 B grape
3 C orange banana grape
任何帮助都会感激不尽。
答案 0 :(得分:3)
# Remove all words from `target$favor` that are not in the dictionary
result <- lapply(strsplit(target$favor, ',| '), function(x) { x[x %in% dictionary] })
result
# [[1]]
# [1] "apple" "banana"
#
# [[2]]
# [1] "grape"
#
# [[3]]
# [1] "orange" "banana" "grape"
# Fill in NAs when the rows have different numbers of items
result <- lapply(result, `length<-`, max(lengths(result)))
# Rebuild the data.frame using the list of words in each row
cbind(target[ , 'user', drop = F], do.call(rbind, result))
# user 1 2 3
# 1 A apple banana <NA>
# 2 B grape <NA> <NA>
# 3 C orange banana grape
请注意,我使用target
阅读了stringsAsFactors = FALSE
,以便strsplit
可以正常工作。
答案 1 :(得分:1)
最好的办法是将str_extract_all
应用到每一行。
library(stringr)
result <- t(apply(target, 1,
function(x) str_extract_all(x[['favor']], dictionary, simplify = TRUE)))
[,1] [,2] [,3] [,4]
[1,] "apple" "banana" "" ""
[2,] "" "" "" "grape"
[3,] "" "banana" "orange" "grape"