ecerulm - 1 year ago 64

R Question

I want to make an existing vector size

`n`

`NA`

`v1 <- 1:10`

v2 <- diff(v1)

length(v2) <- length(v1)

v2

# 1 1 1 1 1 1 1 1 1 NA

But I want to fill the

`NA`

`v2 <- c(NA, diff(v1))`

# NA 1 1 1 1 1 1 1 1 1

But I was hoping that there exist some base R function or library that provides something like

`v2 <- pad(v2, n=length(v1), value=NA)`

Is there anything like that I can use off the self or do I need to define my own function:

`pad <- function(x, n) { # ugly function that doesn't keep the attributes of x`

len.diff <- n - length(x)

c(rep(NA, len.diff), x)

}

pad(1:10, 12) # NA NA 1 2 3 4 5 6 7 8 9 10

Answer Source

Assuming `v1`

has the desired length and `v2`

is shorter (or the same length) these left pad `v2`

with `NA`

values to the length of `v1`

. The first four assume numeric vectors although they can be modified to also work more generally by replacing `NA*v1`

in the code with `rep(NA, length(v1))`

.

```
replace(NA * v1, seq(to = length(v1), length = length(v2)), v2)
rev(replace(NA * v1, seq_along(v2), rev(v2)))
replace(NA * v1, seq_along(v2) + length(v1) - length(v2), v2)
tail(c(NA * v1, v2), length(v1))
c(rep(NA, length(v1) - length(v2)), v2)
```

The fourth is the shortest. The first two and fourth do not involve any explicit arithmetic calculations other than multiplying `v1`

with `NA`

values. The second is likely slow since it involves two applications of `rev`

.