首页 > 解决方案 > 根据向量更新 R 中的列

问题描述

我正在尝试更新数据中存在的每个区域的状态。

有没有更清洁和有效的方法来做到这一点?因为我还必须为其他州重复这个过程。

Seattle <- c("Bellevue","Richmond","Union-Lake")

in.Seattle <- data[which(data$region %in% Seattle),]
in.Seattle = list(in.Seattle$region)
data$State[data$region == unlist(in.Seattle)] <- 'Seattle'

structure(list(region = c("Bellevue","Richmond","Union-Lake", 
"Apatula","Broome"), region = c(2016L, 
2016L, 2016L, 2016L, 2016L, 2016L), x = c(7513L, 30124L, 6807L, 
10191L, 84454L, 6057L)), row.names = c(NA, 6L), class = "data.frame")

标签: rvector

解决方案


一个选项是使用fcase fromdata.table

library(data.table)
setDT(data)[, state := fcase(region %in% Seattle, "Seattle",
                              region %in% another_vec, "another_vec",
                               ....
                               )]

推荐阅读