r - 根据向量更新 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")
解决方案
一个选项是使用fcase
fromdata.table
library(data.table)
setDT(data)[, state := fcase(region %in% Seattle, "Seattle",
region %in% another_vec, "another_vec",
....
)]
推荐阅读
- vue.js - 如何清空 html 标签的内容?
- java - Java CountDownLatch 等待异步回调
- api - 通过 Bitbucket API 更新 Bitbucket 拉取请求的描述
- amazon-web-services - 从 VPC 访问 AWS 网络负载均衡器
- python - 在循环中对列表列表应用条件并获取列表列表作为输出
- javascript - 如何使用firebase函数从父文件夹中读取文件
- go - 如何为 kafka 消费者添加自定义消息反序列化器(使用 sarama lib)
- echarts - 为 echarts 设置全局千位分隔符
- ios - APNS 无法获取 DeviceToken
- url-rewriting - URL 重写规则以删除查询字符串后的斜杠