Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pad a vector with NA from the front?

Tags:

r

I want to make an existing vector size n and use NA. I know I can pad at the end of the vector like so:

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 at the beginnning instead in a generic way. I mean for this particular example I can just

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
like image 457
RubenLaguna Avatar asked Sep 14 '16 08:09

RubenLaguna


3 Answers

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.

like image 144
G. Grothendieck Avatar answered Nov 15 '22 14:11

G. Grothendieck


One option is diff from zoo which also have the na.pad

library(zoo)
as.vector(diff(zoo(v1), na.pad=TRUE))
#[1] NA  1  1  1  1  1  1  1  1  1
like image 20
akrun Avatar answered Nov 15 '22 15:11

akrun


Defining nrValues as the number of elements you want at the start of v2 you could use:

n <- length(v1) v2 <- c(rep(NA,nrValues),v1[nrValues:n])

I'm not familiar with a function that does this, so if you intend to do it multiple times I would create your own function.

like image 34
Christov Avatar answered Nov 15 '22 13:11

Christov