问题描述
我有一个数据框,其中包含一列充满文字的列。很难在其中找到任何正则表达式模式。不过,我感兴趣的是根据预先定义的国家列表提取所有国家。我以为它应该不太难,但是找不到围绕str_extract的方法
这是一个可复制的示例:
data <- data.frame (text_column = c("I travelled to Germany last year,afterwards I visited Poland"," I enjoyed my vacation in Spain","The weather in the Netherlands was not great"))
我有国家列表
country_vector <- c("Germany","Poland","the Netherlands","France")
我想要的是对那些国家/地区匹配文本列,提取所有匹配项,然后将它们旋转到所有匹配项的单独列中。如果没有匹配项,那么我们可以输入NA。
因此,预期结果是:
Country_1 Country_2
Germany Poland
NA NA
the Netherlands NA
鉴于在一栏中可能有多个国家/地区,则最终小标题/ df的ncol必须是具有最多国家/地区的条目的长度。
有人知道如何解决这个问题吗?我已经能够为1个条目做到这一点,但不能为我的整个数据框做到这一点。但是我感觉自己的工作方向错误,必须有一个更简单的解决方案。
temp <- stringr::str_extract(data$text_column,country_vector) %>%
as.data.frame() %>%
magrittr: set_colnames(c("countries")) %>%
dplyr::filter(!is.na(countries))
if (nrow(temp==0)){
temp <- temp %>% add_row(countries = NA) %>%
mutate(order = paste0("country_",seq(1:nrow(.)))) %>%
pivot_wider(.,names_from = order,values_from = countries)
print(temp)
} else {
temp <- temp %>%
mutate(order = paste0("country_",values_from = countries)
print(temp)
}
解决方法
str_extract_all
提供所需的数据:
library(stringr)
str_extract_all(data$text_column,str_c(country_vector,collapse = '|'))
#[[1]]
#[1] "Germany" "Poland"
#[[2]]
#character(0)
#[[3]]
#[1] "the Netherlands"
要获取所需格式的数据,您需要操纵上述输出。
library(dplyr)
bind_rows(lapply(
str_extract_all(data$text_column,collapse = '|')),function(x) if(length(x)) as.data.frame(t(x)) else as.data.frame(t(NA))))
# V1 V2
#1 Germany Poland
#2 <NA> <NA>
#3 the Netherlands <NA>
,
simplify
中有一个str_extract_all
选项,它返回一个matrix
。因此,我们可以直接转换为两列matrix
并用as.data.frame
包装(如果需要data.frame)
library(stringr)
as.data.frame(str_extract_all(data$text_column,collapse = '|'),simplify = TRUE))
# V1 V2
#1 Germany Poland
#2
#3 the Netherlands