Multiple replacement in R

2020-03-03 09:09发布

I want to do multiple replacements in the matrix. For example,

x <-sample(1:20,50,rep=T)
replace(x, x == 4, 2)

Replacing the elements equal to 4 in x with 2 by using replace. But how can I replace x == 4 with 2, x ==3 with 4 and x == 5 with 6.

Is there any built function to replace (4,3,5) respectively with (2,4,6)?

标签: r
3条回答
Melony?
2楼-- · 2020-03-03 09:23

1) Try this:

 replace(seq(20), c(4,3,5), c(2,4,6))[x]

2) Here is a more general approach:

 c(2, 4, 6, x)[match(x, c(4, 3, 5, x))]

This second approach has the form: c(new, x)[match(x, c(old, x))]

查看更多
家丑人穷心不美
3楼-- · 2020-03-03 09:33

I smell a data.table answer cooking but here's an environment lookup approach:

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)

This one begged for a benchmark:

enter image description here

On 10,000 length vector (10 replications):

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
查看更多
▲ chillily
4楼-- · 2020-03-03 09:35

You can do this:

find    <- c(4,3,5)
replace <- c(2,4,6)
found   <- match(x, find)

ifelse(is.na(found), x, replace[found])

or use plyr's mapvalues which uses a similar implementation using match:

library(plyr)
mapvalues(x, find, replace, warn.missing = FALSE)

Both methods work with any kind of data. For character vectors, you could also convert into factors and permute levels.

查看更多
登录 后发表回答