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

如何在R语言中将指定州数据拆分到对应地区新列?

解决方案:将美国各州映射到对应地区列

方法一:用逻辑值标记归属地区

先定义各地区包含的州,再通过dplyr::mutate结合%in%运算符为每个地区创建新列,逻辑值TRUE表示该州属于对应地区,FALSE表示不属于。

代码示例:

# 加载dplyr包(未安装先运行 install.packages("dplyr"))
library(dplyr)

# 定义各地区的州列表
new_england_states <- c("Maine", "Vermont")
south_states <- c("Georgia", "Florida")
west_coast_states <- c("California", "Washington")

# 你的原始数据
States <- c("Maine", "Georgia", "California", "Vermont", "Florida", "Washington")
Players <- c("1a", "1b", "2a", "2b", "3a", "3b")
Score <- c(15, 21, 8, 17, 12, 11)
data <- data.frame(States, Players, Score)

# 添加地区列
data <- data %>%
  mutate(
    New_England = States %in% new_england_states,
    South = States %in% south_states,
    West_coast = States %in% west_coast_states
  )

# 查看结果
print(data)

运行后输出:

States Players Score New_England South West_coast
1       Maine     1a    15        TRUE FALSE      FALSE
2     Georgia     1b    21       FALSE  TRUE      FALSE
3  California     2a     8       FALSE FALSE       TRUE
4     Vermont     2b    17        TRUE FALSE      FALSE
5     Florida     3a    12       FALSE  TRUE      FALSE
6 Washington     3b    11       FALSE FALSE       TRUE

方法二:用州名填充对应地区列(其余为NA)

如果希望对应地区列仅显示归属该地区的州名,其余位置用NA填充,可改用ifelse函数:

data <- data %>%
  mutate(
    New_England = ifelse(States %in% new_england_states, States, NA),
    South = ifelse(States %in% south_states, States, NA),
    West_coast = ifelse(States %in% west_coast_states, States, NA)
  )

print(data)

运行后输出:

States Players Score New_England   South West_coast
1       Maine     1a    15        Maine    NA        NA
2     Georgia     1b    21         NA Georgia        NA
3  California     2a     8         NA    NA  California
4     Vermont     2b    17       Vermont    NA        NA
5     Florida     3a    12         NA Florida        NA
6 Washington     3b    11         NA    NA Washington

常见问题说明

如果你之前使用mutate失败,大概率是判断条件写法有误——比如逐个用==判断多个州(这种写法仅能匹配单个值),正确做法是用%in%判断州是否属于某一地区的州列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:12:46