r - 如何切换列中的值?
问题描述
我有以下专栏:
ColA ColB
1 f
2 f
1 f
1 f
2 f
如何在 ColA 中将 1 切换为 2 并将 2 切换为 1?
解决方案
如果只有 1 和 2 个值,我们可以使用算术来改变值
df1$ColA <- with(df1, 2- ColA + 1)
df1$ColA
#[1] 2 1 2 2 1
或使用match
match(df1$ColA, c(2, 1))
或使用factor
factor(df1$ColA, levels = 1:2, labels = 2:1)
数据
df1 <- structure(list(ColA = c(1L, 2L, 1L, 1L, 2L), ColB = c("f", "f",
"f", "f", "f")), class = "data.frame", row.names = c(NA, -5L))
推荐阅读
- python - 在排序一个列表期间将不同列表中的相关元素保持在一起
- c# - 如何对通用列表对象进行排序
- javascript - 向和从 js 服务器发送数据的基本方法?
- json - 使用 Pyspark 处理 JSON 结构
- amazon-web-services - 为什么角色假设应该在 lambda 内部完成?
- html - 如何将数值绑定到 CSS 以创建时间线?
- docker - 如何为 docker compose 环境变量设置运行时变量
- javascript - 仅在 Javascript 中具有不同段落的动态 Div
- tsql - 表格模型中的测量列未在浏览器中显示正确的值
- javascript - 调用此函数时如何获取返回值?