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

在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:54:26