Replace given value in vector Replace given value in vector r r

Replace given value in vector


Perhaps replace is what you are looking for:

> x = c(3, 2, 1, 0, 4, 0)> replace(x, x==0, 1)[1] 3 2 1 1 4 1

Or, if you don't have x (any specific reason why not?):

replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)

Many people are familiar with gsub, so you can also try either of the following:

as.numeric(gsub(0, 1, x))as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))

Update

After reading the comments, perhaps with is an option:

with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))


Another simpler option is to do:

 > x = c(1, 1, 2, 4, 5, 2, 1, 3, 2) > x[x==1] <- 0 > x [1] 0 0 2 4 5 2 0 3 2


Why the fuss?

replace(haystack, haystack %in% needles, replacements)

Demo:

haystack <- c("q", "w", "e", "r", "t", "y")needles <- c("q", "w")replacements <- c("a", "z")replace(haystack, haystack %in% needles, replacements)#> [1] "a" "z" "e" "r" "t" "y"