How to cbind vectors of different length without repetition of elements of the smaller vector in R?


We can join vectors by columns using cbind and it does not matter whether these vectors are of same length or not. If the vectors are of same length then all the values of both the vectors are printed but if the length of these vectors are different then the values of the smaller vector gets repeated. But we might not want to repeat the values/elements of the smaller vector and it is possible by setting the length of the smaller vector to the length of larger vector, this will create NA values in the smaller at places where the original vector does not have any values.

Example 1

x1<-c(4,7,8,12)
x2<-1:20
n<-max(length(x1),length(x2))
length(x1)<-n
cbind(x1,x2)

Output

 x1 x2
[1,] 4 1
[2,] 7 2
[3,] 8 3
[4,] 12 4
[5,] NA 5
[6,] NA 6
[7,] NA 7
[8,] NA 8
[9,] NA 9
[10,] NA 10
[11,] NA 11
[12,] NA 12
[13,] NA 13
[14,] NA 14
[15,] NA 15
[16,] NA 16
[17,] NA 17
[18,] NA 18
[19,] NA 19
[20,] NA 20

Example 2

y1<-c("A","B","C","D","E")
y2<-LETTERS[1:20]
n<-max(length(y1),length(y2))
length(y1)<-n
cbind(y1,y2)

Output

y1 y2
[1,] "A" "A"
[2,] "B" "B"
[3,] "C" "C"
[4,] "D" "D"
[5,] "E" "E"
[6,] NA "F"
[7,] NA "G"
[8,] NA "H"
[9,] NA "I"
[10,] NA "J"
[11,] NA "K"
[12,] NA "L"
[13,] NA "M"
[14,] NA "N"
[15,] NA "O"
[16,] NA "P"
[17,] NA "Q"
[18,] NA "R"
[19,] NA "S"
[20,] NA "T"

Example 3

z1<-1:20
z2<-16:20
n<-max(length(z1),length(z2))
length(z2)<-n
cbind(z1,z2)

Output

z1 z2
[1,] 1 16
[2,] 2 17
[3,] 3 18
[4,] 4 19
[5,] 5 20
[6,] 6 NA
[7,] 7 NA
[8,] 8 NA
[9,] 9 NA
[10,] 10 NA
[11,] 11 NA
[12,] 12 NA
[13,] 13 NA
[14,] 14 NA
[15,] 15 NA
[16,] 16 NA
[17,] 17 NA
[18,] 18 NA
[19,] 19 NA
[20,] 20 NA

Updated on: 21-Aug-2020

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements