Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...