在R语言中根据另一变量的特定值为新变量赋值
给美国州分配区域的R语言实现
核心思路
不用手动遍历行,直接通过预定义州-区域映射向量结合R的向量匹配功能实现,高效处理3000行数据,且无需外部文件。
步骤1:定义48个相邻州的区域映射
先在代码里创建命名向量,把每个州对应到目标区域(可根据需求调整划分规则):
# 定义州与区域的映射关系 state_region <- c( # 南部区域 "Alabama" = "South", "Arkansas" = "South", "Delaware" = "South", "Florida" = "South", "Georgia" = "South", "Kentucky" = "South", "Louisiana" = "South", "Maryland" = "South", "Mississippi" = "South", "North Carolina" = "South", "Oklahoma" = "South", "South Carolina" = "South", "Tennessee" = "South", "Virginia" = "South", "West Virginia" = "South", # 西部区域 "Arizona" = "West", "California" = "West", "Colorado" = "West", "Idaho" = "West", "Montana" = "West", "Nevada" = "West", "New Mexico" = "West", "Oregon" = "West", "Utah" = "West", "Washington" = "West", "Wyoming" = "West", # 中西部区域 "Illinois" = "Midwest", "Indiana" = "Midwest", "Iowa" = "Midwest", "Kansas" = "Midwest", "Michigan" = "Midwest", "Minnesota" = "Midwest", "Missouri" = "Midwest", "Nebraska" = "Midwest", "North Dakota" = "Midwest", "Ohio" = "Midwest", "South Dakota" = "Midwest", "Wisconsin" = "Midwest", # 中部区域(示例中的Texas) "Texas" = "Central", # 东北部区域 "Connecticut" = "Northeast", "Maine" = "Northeast", "Massachusetts" = "Northeast", "New Hampshire" = "Northeast", "New Jersey" = "Northeast", "New York" = "Northeast", "Pennsylvania" = "Northeast", "Rhode Island" = "Northeast", "Vermont" = "Northeast" )
步骤2:给数据框添加region列
方法一:Base R 实现
假设你的数据框名为df,包含state列,直接通过向量匹配赋值:
# 添加region列 df$region <- state_region[df$state] # 查看结果示例 head(df[, c("state", "region")])
方法二:dplyr 实现(更简洁)
如果你习惯用tidyverse工具链:
library(dplyr) df <- df %>% mutate(region = state_region[state]) # 查看结果 df %>% select(state, region) %>% head()
示例输出
State Region
Wyoming West
Michigan Midwest
Alabama South
Georgia South
California West
Texas Central
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

