如何从字符串中提取美国州名?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.
Step 1: Load a handy string package (optional but recommended)
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
\\bword boundary prevents false matches (e.g., it won't pick up "Arkansasville" as "Arkansas") - R's built-in
state.nameis 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

