我有几个变量,数据如下所示:
| x1 |x2 |
| apple | orange |
| banana | apple |
当然,我还有其他不想改变的变量。 我想替换这样的值,仅适用于 x1 和 x2
apple - change to 1
orange - change to 2
banana - change to 3
如何实现?
我可以手动一一赋值。但我正在寻找有效的解决方案。
使用查找表,在本例中采用命名向量的形式。该向量是根据数据集创建的(名称顺序除外)。在下面的代码中,在
unique(unlist(.))
之后,值 "orange"
是第三个,而不是第二个。这必须手动更改。
df1 <- read.table(text = "
| x1 |x2 |
| apple | orange |
| banana | apple |
", header = TRUE, sep = "|", strip.white = TRUE)
df1 <- df1[2:3]
df1
#> x1 x2
#> 1 apple orange
#> 2 banana apple
lookup <- unique(unlist(df1))
lookup <- setNames(seq_along(lookup), lookup[c(1L, 3L, 2L)])
df1[] <- lapply(df1, \(x) {
lookup[match(x, names(lookup))]
})
df1
#> x1 x2
#> 1 1 2
#> 2 3 1
创建于 2023-09-18,使用 reprex v2.0.2