首页 > 解决方案 > 如何切换列中的值?

问题描述

我有以下专栏:

ColA ColB
1     f
2     f
1     f
1     f
2     f

如何在 ColA 中将 1 切换为 2 并将 2 切换为 1?

标签: r

解决方案


如果只有 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))

推荐阅读