m_c
m_c

Reputation: 516

Insert NA elements in vector

I have a vector:

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

I would like to add 23 NA elements before each element of x

Upvotes: 0

Views: 2598

Answers (2)

akrun
akrun

Reputation: 887078

We can do this with vectorization

replace(rep(NA, 23*length(x) + length(x)), rep(c(FALSE, TRUE), c(23, 1)), x) 
#[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA  1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
#[43] NA NA NA NA NA  2 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA  3 NA NA NA NA NA NA NA NA NA NA NA NA
#[85] NA NA NA NA NA NA NA NA NA NA NA  4

Or another option is to create a matrix, replace the last row with 'x' and convert it to vector

m1 <- matrix(rep(rep(NA, 24), length(x)), nrow = length(x))
m1[,24] <- x
c(t(m1)) 

Upvotes: 1

DatamineR
DatamineR

Reputation: 9618

Maybe like this?

c(sapply(x, function(x) c(rep(NA,23),x)))

Upvotes: 5

Related Questions