Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate vectors of different lengths without recycling and without using a loop?

Tags:

r

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?

like image 943
David J. Bosak Avatar asked Dec 13 '22 06:12

David J. Bosak


1 Answers

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)

like image 88
norie Avatar answered Dec 22 '22 00:12

norie