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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With