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

如何在R中根据预设州区域向量为tibble批量新增Region列

以下实现默认你的tibble中存储州全称的列名为state,如果列名不同请替换为实际列名

方法1:使用dplyr的case_when(推荐,逻辑直观易维护)

你需要先加载dplyr包(tidyverse集合已包含该包),代码如下:

library(dplyr)

df <- df %>%
  mutate(Region = case_when(
    state %in% West ~ "West",
    state %in% Midwest ~ "Midwest",
    state %in% South ~ "South",
    state %in% Northeast ~ "Northeast",
    # 匹配不到的内容设为缺失,方便你排查拼写或区域划分错误
    .default = NA_character_
  ))

方法2:基础R实现,无需额外加载包

通过构建命名查找向量实现匹配赋值:

# 构造查找表,键为州名,值为对应区域
region_lookup <- c(
  setNames(rep("West", length(West)), West),
  setNames(rep("Midwest", length(Midwest)), Midwest),
  setNames(rep("South", length(South)), South),
  setNames(rep("Northeast", length(Northeast)), Northeast)
)

# 批量匹配赋值
df$Region <- region_lookup[df$state]

注意事项

  • 你提供的Northeast向量中重复录入了两次Wisconsin,建议先执行Northeast <- unique(Northeast)去重,避免后续匹配异常
  • 当前你预设的区域划分和美国人口普查局的标准划分存在差异,比如俄克拉荷马、德州通常划归南部,威斯康星、伊利诺伊等属于中西部,你可以根据实际需求调整区域对应向量后再执行上述代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:57:04