我有一些推特作者的位置数据,我想将其重新分类到国家。例如,取一个美国"States"的向量,我想检查(regex(是否匹配,并添加一个"state";美国";进入国家/地区栏。
示例数据:
states = c("CA", "OH", "FL", "TX", "MN") # all the states
tweets$location = data.frame("my bed", "Minneapolis, MN", "Paris, France", "Los Angeles, CA")
我尝试过的:
# This seems to do the matching part well
filter(str_detect(location, paste(usa_data$Code, collapse = "|")))
# nested for loop
for (i in length(tweets$location)){
for (state in states){
if (grepl(state, tweets$location[i])){
tweets$country[i] = "USA"
break
}
}
}
期望输出(基于示例输入(:
tweets$country = data.frame(NA, "USA", NA, "USA")
我是R的新手,因此任何帮助都将不胜感激。
我们可以将grepl
和ifelse
一起用于基本R解决方案:
states = c("CA", "OH", "FL", "TX", "MN") # all the states
tweets$location = data.frame("my bed", "Minneapolis, MN", "Paris, France", "Los Angeles, CA")
regex <- paste0("\b(?:", paste(states, collapse="|"), ")\b")
tweets$country <- ifelse(grepl(regex, tweets$location), "USA", NA)
如果您更喜欢dplyr
解决方案,但与Tim的答案非常相似
library(dplyr)
states <- c("CA", "OH", "FL", "TX", "MN") # all the states
tweets <- tibble(location = c(
"my bed", "Minneapolis, MN", "Paris, France",
"Los Angeles, CA"
))
tweets %>%
mutate(country = if_else(stringr::str_detect(
string = location,
pattern = paste0(
"\b(?:", paste(states,
collapse = "|"
),
")\b"
)
),
"United States", "NA"
))