Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: replace a value of a vector with multiple values

Let's say, I have a vector a with length(a) = l and l >= 1.

The element "x" occurs at least one time in a, but we don't know an exact position.

I want to replace every "x" in a with the values c(1,2,3)

For example: a = ("y","x","z"), then I want the result after the replacement to be a = ("y",1,2,3,"z").

I thought of doing it this way:

l <- length(a)
pos.x <- which(a == "x")

if(l == 1L & pos.x == 1L) {
  a <- c(1,2,3)
} else if (l > 1L & pos.x == 1) {
  a <- c(1,2,3,a[-1])
} else if (l > 1L & pos.x == l) {
  a <- c(a[-l],1,2,3)
} else if (l >= 3 & pos.x != 1 & pos.x != l) {
  a <- c(a[1:(pos.x - 1)],1,2,3,a[(pos.x + 1):l])
}

While this code does work, my question would be wether there is a more 'elegant' way to solve this problem, that needs less processing power, and that could replace more than one "x".

Thank you!

like image 713
Galvin Hoang Avatar asked Dec 18 '25 08:12

Galvin Hoang


1 Answers

Here's a simple vectorized solution with base R -

a <- c("y","x","z","y","x","z") # vector to search
b <- 1:3 # replacement values

a <- rep(a, 1 + (length(b) - 1)*(a == "x")) # repeat only "x" length(b) times

a[a == "x"] <- b # replace "x" with replacement values i.e. b

[1] "y" "1" "2" "3" "z" "y" "1" "2" "3" "z"
like image 158
Shree Avatar answered Dec 19 '25 23:12

Shree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!