You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串中提取美国州名?R语言批量实现方法咨询

Got it, let's solve this efficiently so you don't have to write 42 lines of repetitive code. Here's how to do it cleanly in R:

解决方案

First, take advantage of R's built-in state.name dataset—it already includes all 50 US state names, so you don't have to manually type out every single one. Combine that with regex and string tools to extract state names in one go.

We'll use stringr for its intuitive string extraction function:

library(stringr)

Step 2: Set up your sample data

Use the dataframe you provided:

df <- data.frame(string = c("The quick brown Arizona","jumps over the Alabama","dog Arkansas"))

Step 3: Build a regex pattern for state names

We'll turn all state names into a single regex pattern, with word boundaries (\\b) to ensure we match full state name words (no partial matches like "Arizonax" being mistaken for "Arizona"):

# Use built-in state.name to get all state names
state_pattern <- paste0("\\b(", paste(state.name, collapse = "|"), ")\\b")

Step 4: Extract state names in bulk

Use str_extract() to pull the matching state name from each row and add it as a new column:

df$state <- str_extract(df$string, state_pattern)

Check the result

After running the code, your dataframe will look like this:

> df
                     string    state
1 The quick brown brown Arizona Arizona
2 jumps over the Alabama Alabama
3             dog Arkansas Arkansas

Base R Alternative (no extra packages needed)

If you prefer not to load external packages, use Base R's sapply() and grepl() combo:

df$state <- sapply(df$string, function(x) {
  # Find all state names matching the current string
  matches <- state.name[grepl(paste0("\\b", state.name, "\\b"), x)]
  # Return the first match (or NA if none exist)
  if(length(matches) > 0) matches[1] else NA
})

Key Notes

  • The \\b word boundary prevents false matches (e.g., it won't pick up "Arkansasville" as "Arkansas")
  • R's built-in state.name is way more reliable than manually typing 42+ state names
  • Rows without a state name will return NA, making it easy to filter or clean later

内容的提问来源于stack exchange,提问作者John Clegg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:51:11