如何一次替换多个值

Lat*_*ter 7 r

我想一次用特定的其他值替换向量中的不同值.

在我正在解决的问题中:

  • 1应该替换为2,
  • 2与4,
  • 3与6,
  • 4与8,
  • 5与1,
  • 6与3,
  • 7与5和
  • 8与7.

以便:

x <- c(4, 2, 0, 7, 5, 7, 8, 9)
x
[1] 4 2 0 7 5 7 8 9
Run Code Online (Sandbox Code Playgroud)

将被转换为:

[1] 8 4 0 5 1 5 7 9
Run Code Online (Sandbox Code Playgroud)

更换后.

我尝试过使用:

x[x == 1] <- 2
x[x == 2] <- 4
Run Code Online (Sandbox Code Playgroud)

等等,但这导致1被7替换.

没有使用任何软件包,这个问题最简单的解决方案是什么?

Jaa*_*aap 7

可能的解决方案:

old <- 1:8
new <- c(2,4,6,8,1,3,5,7)

x[x %in% old] <- new[match(x, old, nomatch = 0)]
Run Code Online (Sandbox Code Playgroud)

这使:

> x
[1] 8 4 0 5 1 5 7 9
Run Code Online (Sandbox Code Playgroud)

这是做什么的:

  • 创建两个向量:old包含需要替换的值和new相应的替换.
  • 使用match,看看从价值观x发生old.使用nomatch = 0删除NA的.这导致了位置的索引向量中oldx
  • 然后可以使用该索引向量进行索引new.
  • 仅从分配值new到的位置x存在于old:x[x %in% old]


MKR*_*MKR 6

如果可以为所有值定义转换对,则factor可以选择先转换为整数再转换为整数。

old <- 0:9
new <- c(0,2,4,6,8,1,3,5,7,9)

as.integer(as.character(factor(x, old, new)))
# [1] 8 4 0 5 1 5 7 9
Run Code Online (Sandbox Code Playgroud)