1

I'm learning how to use this program. I have a vector with values called, for example, X. I need to add one zero after the value 11 in my vector, so I have used the function append:

X<- append(X, 0, after=11)

It works properly, but I have problems when I want to add two zeroes between two different values in the vector. How can I indicate to the function that I want one zero after the values 3 and 11? I have tried with after= c(3,11) and after= (3,11), and it doesn't work.

For now, I have fixed it by writing it again but I'm sure there is a better solution:

X<- append(X, 0, after=3); X<- append(X, 0, after=11)

Thank you and I'm sorry cause my english is not very good

IRTFM
  • 258,963
  • 21
  • 364
  • 487

1 Answers1

0

If we are inserting at multiple positions

nvalues <- 2
pos <- c(3, 5, 7)
pos1 <- c(pos[1], seq_along(pos[-1]) * nvalues + pos[-1])
for(i in seq_along(pos)) X <- append(vec, c(0, 0), after = pos1[i])
X
#[1]  3  4  2  0  0  5  3  0  0  9 10  0  0 12 14

It can be wrapped into a function

f1 <- function(vec, nvalues, posvec, value) {
    posvec1 <- c(posvec[1], seq_along(posvec[-1]) * nvalues + 
           posvec[-1])
    for(i in seq_along(posvec)) vec <-  append(vec, 
               rep(value, nvalues), after = posvec1[i])
    vec
 }



f1(X, 1, c(3, 5, 7), 0)
#[1]  3  4  2  0  5  3  0  9 10  0 12 14
f1(X, 2, c(3, 5, 7), 0)
#[1]  3  4  2  0  0  5  3  0  0  9 10  0  0 12 14
f1(X, 3, c(3, 5, 7), 0)
#[1]  3  4  2  0  0  0  5  3  0  0  0  9 10  0  0  0 12 14

data

X <- c(3, 4, 2, 5, 3, 9, 10, 12, 14)
akrun
  • 874,273
  • 37
  • 540
  • 662