Reputation: 894
Is there any alternative method of R for the problem explained here: How to insert elements in a vector at regular intervals in Matlab
Namely, from a vector x <- c(1,2,3,4,5,6,7,8,9,10,11,12)
, I want to obtain a vector y
given by
y <- c(0, 1, 2, 3,
0, 4, 5, 6,
0, 7, 8, 9,
0,10,11,12)
... I found the following page,... maybe duplicate
R: insert elements into vector (a variation)
Edit I slighly modified the answer of @jay.sf . I think his interval.length
is not our intuitive interval length.
x <- 1:16
interval.length <- 2
co_interval.length <- length(x)/interval.length
as.vector(t(cbind(0, matrix(x, co_interval.length, byrow=T))))
[1] 0 1 2 0 3 4 0 5 6 0 7 8 0 9 10 0 11 12 0 13 14 0 15 16
Upvotes: 2
Views: 287
Reputation: 173793
Another way is to make use of arithmetical indexing:
y <- numeric(16)
y[x + 1 + (x - 1) %/% 3] <- x
y
#> [1] 0 1 2 3 0 4 5 6 0 7 8 9 0 10 11 12
Upvotes: 2
Reputation: 72593
You could make a matrix and coerce it into a vector.
interval.length <- 4
as.vector(t(cbind(0, matrix(x, interval.length, byrow=T))))
# [1] 0 1 2 3 0 4 5 6 0 7 8 9 0 10 11 12
Upvotes: 4