Let's say I have two vectors of different lengths:
v1 <- c("A", "B", "C", "D", "E")
v2 <- c("F", "G", "H")
I want to concatenate these two vectors. But I don't want to recycle the short vector. I just want NAs for the missing elements. So I want this:
[1] "A-F" "B-G" "C-H" "D-NA" "E-NA"
If I use paste, the short vector gets recycled:
paste(v1, v2, sep = "-")
# [1] "A-F" "B-G" "C-H" "D-F" "E-G"
I could do it easily with a loop:
v3 <- c()
for (i in seq_along(v1)) {
v3[i] <- paste(v1[i], v2[i], sep = "-")
}
v3
# [1] "A-F" "B-G" "C-H" "D-NA" "E-NA"
But if anyone on StackOverflow discovered I was extending a vector dynamically inside a loop, they would have a conniption.
So, how can I concatenate two vectors of different lengths without recycling and without using a loop?
Find the length of the longest vector and set the length of each vector to that, then concatenate.
v1 <- c("A", "B", "C", "D", "E")
v2 <- c("F", "G", "H")
n <- max(length(v1), length(v2))
length(v1) <- n
length(v2) <- n
paste(v1, v2, sep = "-")
#> [1] "A-F" "B-G" "C-H" "D-NA" "E-NA"
Created on 2021-09-26 by the reprex package (v2.0.1)
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