[Solved] Replace some component value in a vector with some other value


The idiomatic r way is to use [<-, in the form
x[index] <- result

If you are dealing with integers / factors or character variables, then == will work reliably for the indexing,

x <- rep(1:5,3)
x[x==3] <- 1
x[x==4] <- 2

x
## [1] 1 2 1 2 5 1 2 1 2 5 1 2 1 2 5

The car has a useful function recode (which is a wrapper for [<-), that will let you combine all the recoding in a single call

eg

library(car)

x <- rep(1:5,3)

xr <- recode(x, '3=1; 4=2')

x
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
xr
## [1] 1 2 1 2 5 1 2 1 2 5 1 2 1 2 5

Thanks to @joran for mentioning mapvalues from the plyr package, another wrapper for [<-

x <- rep(1:5,3)
mapvalues(x, from = c(3,1), to = c(1,2))

plyr::revalue is a wrapper for mapvalues specifically factor or character variables.

2

solved Replace some component value in a vector with some other value