我在r。
中有一个单词矢量words = c("Awesome","Loss","Good","Bad")
而且,我在r
中有以下数据框ID Response
1 Today is an awesome day
2 Yesterday was a bad day,but today it is good
3 I have losses today
我想要做的是应该提取响应列中匹配的单词并将其插入到dataframe中的新列中。最终输出应该如下所示
ID Response Match Count
1 Today is an awesome day Awesome 1
2 Yesterday was a bad day Bad,Good 2
,but today it is good
3 I have losses today Loss 1
我在r
中做了以下sapply(words,grepl,df$Response)
它匹配单词,但我如何以所需格式获取数据帧? 请帮忙。
答案 0 :(得分:4)
使用基础R - (在Dre $ Counts的简明答案中也可以获得PereG的帮助)
# extract the list of matching words
x <- sapply(words, function(x) grepl(tolower(x), tolower(df$Response)))
# paste the matching words together
df$Words <- apply(x, 1, function(i) paste0(names(i)[i], collapse = ","))
# count the number of matching words
df$Count <- apply(x, 1, function(i) sum(i))
# df
# ID Response Words Count
#1 1 Today is an awesome day Awesome 1
#2 2 Yesterday was a bad day,but today it is good Good,Bad 2
#3 3 I have losses today Loss 1
答案 1 :(得分:0)
这是另一个选项,用于将匹配项存储在list
s:
vgrepl <- Vectorize(grepl, "pattern")
df$Match <- lapply(df$Response, function(x)
words[vgrepl(words, x, ignore.case=T)]
)
df$Count <- lengths(df$Match)
答案 2 :(得分:0)
使用df作为数据帧并使用stringr,以下内容也可以使用:
matches <- sapply(1:length(words), function(i) str_extract_all(tolower(df$Response),
tolower(words[i]), simplify = TRUE))
df$Match <- gsub('[,][,]+|^,|,$', '', apply(matches, 1, paste, collapse=','))
df$Count <- apply(matches, 1, function(x) sum(x != ''))
head(df)
# ID Response Match Count
#1 1 Today is an awesome day awesome 1
#2 2 Yesterday was a bad day,but today it is good good,bad 2
#3 3 I have losses today loss 1
答案 3 :(得分:0)
tidyverse
中的解决方案/建议。它报告实际匹配,而不是不区分大小写的模式,但它应足以用于说明目的。
library(stringr)
library(dplyr)
library(purrr)
words <- c("Awesome", "Loss", "Good", "Bad")
"ID;Response
1;Today is an awesome day
2;Yesterday was a bad day,but today it is good
3;I have losses today" %>%
textConnection %>%
read.table(header = TRUE,
sep = ";",
stringsAsFactors = FALSE) ->
d
d %>%
mutate(matches = str_extract_all(
Response,
str_c(words, collapse = "|") %>% regex(ignore_case = T)),
Match = map_chr(matches, str_c, collapse = ","),
Count = map_int(matches, length))