我想一次用特定的其他值替换向量中的不同值.
在我正在解决的问题中:
以便:
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替换.
没有使用任何软件包,这个问题最简单的解决方案是什么?
可能的解决方案:
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)
这使:
Run Code Online (Sandbox Code Playgroud)> x [1] 8 4 0 5 1 5 7 9
这是做什么的:
old包含需要替换的值和new相应的替换.match,看看从价值观x发生old.使用nomatch = 0删除NA的.这导致了位置的索引向量中old的x值new.new到的位置x存在于old:x[x %in% old]如果可以为所有值定义转换对,则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)