Barnaby
Barnaby

Reputation: 1480

Make two vectors of different lengths equal in length

I have two vectors of different lenghts. How can I start both series so their ends concide.

x<-c(1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6)
y<-c(1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4)

I do it with the code below but I guess there must be a more elegant way

x<-x[((length(x)-length(y))+1):length(x)]

x
 [1]  3  4  5  6  7  8  9 10 11 12  1  2  3  4  5  6
y
 [1]  1  2  3  4  5  6  7  8  9 10 11 12  1  2  3  4

Upvotes: 2

Views: 3479

Answers (1)

Calimo
Calimo

Reputation: 7949

Use tail, and min to determine the shortest vector:

shortest <- min(length(x), length(y))
y <- tail(y, shortest)
x <- tail(x, shortest)

Upvotes: 4

Related Questions