-1

so lets say I have

x = 1,4,2
i = 2
j = 4 
k = 3 

So i = 2 and j = 4, the point is i need to place k (3) between the numbers i,j in x so the result would be x = 1,4,3,2. I need it to work in a cycle because the numbers in i,j,k always change and so does the length of x when a new number from k is placed in x. The new x after step one is x = 1,4,3,2 and lets say new values:

i = 4
j = 3
k = 5  so again in the cycle it should place 5 in x between 4 and 3 so final x = 1,4,5,3,2

Is there a way i could do it?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

2 Answers2

1

When i is always the number before j,

You could use append function:

ie:

x = c(1,4,2)
i = 4 
k = 3 

x <- append(x, k, match(i, x))
x
[1] 1 4 3 2

 i = 4
 k = 5
x <- append(x, k, match(i, x))
x
[1] 1 4 5 3 2

Putting this in a function:

insert <- function(x, k, i){
    append(x, k, match(i, x))
}

Note that you did not specify what would happen if you had more than 1 four in your vector. ie x<- c(1,4,2,4,2) where exactly do you want to place the 3? Is it after the first four or the second four? etc

Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Yeah so i and j are always generated from x so in the first case when x = 1,4,2 i and j were randomly picked from x thats why i = 2 and j = 4, its the numbers from x,so the numbers in x dont repeat. Sorry if i dont explaint it very well im new in this – Obrazdoby Nov 15 '20 at 10:32
  • @Obrazdoby since the numbers in x dont repeat, the function I gave above is sufficient – Onyambu Nov 15 '20 at 14:51
0

You can try this function :

insert_after <- function(x, i, k) {
  ind <- match(i, x)
  new_inds <- sort(c(seq_along(x), ind))
  new_x <- x[new_inds]
  new_x[duplicated(new_inds)] <- k
  new_x
}
x = c(1,4,2)
x <- insert_after(x, 4, 3)
x
#[1] 1 4 3 2

x <- insert_after(x, 4, 5)
x
#[1] 1 4 5 3 2
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213