我想在矩阵中做多次替换.例如,
x <-sample(1:20,50,rep=T)
replace(x, x == 4, 2)
Run Code Online (Sandbox Code Playgroud)
使用replace替换x中的4等于2的元素.但是,我怎么能代替 x == 4用2,x ==3用4而x == 5用6.
是否有任何内置功能(4,3,5)分别替换(2,4,6)?
G. *_*eck 10
1)试试这个:
replace(seq(20), c(4,3,5), c(2,4,6))[x]
Run Code Online (Sandbox Code Playgroud)
2)这是一个更通用的方法:
c(2, 4, 6, x)[match(x, c(4, 3, 5, x))]
Run Code Online (Sandbox Code Playgroud)
第二种方法的形式如下: c(new, x)[match(x, c(old, x))]
我闻到了data.table回答烹饪,但这是一个环境查找方法:
n <-50; set.seed(10)
x <-sample(1:20,50,rep=T)
inputs <- c(4,3,5)
outputs <- c(2,4,6)
library(qdap)
lookup(x, inputs, outputs, missing = NULL)
Run Code Online (Sandbox Code Playgroud)
这个请求基准:

在10,000长度矢量(10次重复):
Unit: microseconds
expr min lq median uq max neval
LOOKUP() 9875.384 9992.475 10236.9230 10571.405 11588.846 10
REPLACE() 76.973 85.837 94.7005 104.031 111.961 10
PLYR() 904.082 924.142 952.8315 973.124 1017.442 10
MATCH() 1796.034 1825.423 1864.3760 1881.870 1902.396 10
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
find <- c(4,3,5)
replace <- c(2,4,6)
found <- match(x, find)
ifelse(is.na(found), x, replace[found])
Run Code Online (Sandbox Code Playgroud)
或者使用plyr的mapvalues,其使用了利用类似的实现match:
library(plyr)
mapvalues(x, find, replace, warn.missing = FALSE)
Run Code Online (Sandbox Code Playgroud)
这两种方法都适用于任何类型的数据.对于角色向量,您还可以转换为因子和置换级别.