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

Time:09-27

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?

CodePudding user response:

We could create a list. Add NA's to make equal length. then paste the elements of the list:

my_list <- list(v1, v2)
my_list1 <- lapply(my_list, `length<-`, max(lengths(my_list)))
paste(my_list1[[1]], my_list1[[2]], sep="-")

[1] "A-F"  "B-G"  "C-H"  "D-NA" "E-NA"

CodePudding user response:

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)

CodePudding user response:

We can also use

 do.call(paste, c(as.data.frame(stringi::stri_list2matrix(list(v1, v2))), sep="-"))
[1] "A-F"  "B-G"  "C-H"  "D-NA" "E-NA"

CodePudding user response:

You could complete the shorter vector with "NA"

v1 <- c("A", "B", "C", "D", "E")
v2 <- c("F", "G", "H")

n_v1 <- length(v1)
n_v2 <- length(v2)

if(n_v1 > n_v2){
  paste(v1,c(v2,rep("NA",(n_v1-n_v2))),sep = "-")
  }

[1] "A-F"  "B-G"  "C-H"  "D-NA" "E-NA"
  •  Tags:  
  • r
  • Related