Rilcon42 - 4 months ago 20

R Question

**This is not a regex problem**.

I am trying to correct for lookahead bias in data, basically to move the values up by 1. This is what I came up with. Does anyone have a better/faster/ built-in method to do this?

`d<-c(1,2,3,4)`

#correct for lookahead bias, move values up by 1

e<-d[-c(1)]

length(e)<-length(d)

cbind(d,e)

> cbind(d,e)

d e

[1,] 1 2

[2,] 2 3

[3,] 3 4

[4,] 4 NA

Answer

There are a few ways I could think of to do this. Both are fairly concise one liners:

`base`

```
cbind(d, c(d[-1], NA))
```

`data.table`

```
rev(data.table::shift(rev(d), 1))
```

If we want to write it as a function, we can do that too. Note that this function does not attempt to error handle anything.

```
shift_up <- function(x, n = 1) c(x[-(1:n)], rep(NA, n))
```

Which is *very useful* for fans of the comic series *Batman*:

```
d <- 1:16
shift_up(d, 16)
# [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA #BATMAN!
```