Mikkel
Mikkel

Reputation: 33

Move numbers up and down in vector

I want to move data in a vector to test if it becomes linearly dependent of another data set. What I'm missing is an efficient way to do something like this.

v1 <- c(1,2,3,4)

v2 <- c(NA,v1[1:3])

v3 <- c(v1[2:4],NA)

Is it possible to do something similar to this:

v2 <- v1[NA,T,T,T]

Upvotes: 3

Views: 102

Answers (2)

Mike Wise
Mike Wise

Reputation: 22807

There is this - which is in the spirt of what you are looking for:

v222 <- v1[c(NA,1:3)]

But I am guessing that the original is faster.

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use data.table

library(data.table)
shift(v1, 0:1)
shift(v1, 0:1, type='lead')

Upvotes: 3

Related Questions