1

How do we append a single value to multiple positions in a vector?

x=c(1,2,3)
append(x, "a", c(1,3))
[1] "1" "a" "2" "3"

Warning messages:
1: In if (!after) c(values, x) else if (after >= lengx) c(x, values) else c(x[1L:after],  :
  條件的長度 > 1,因此只能用其第一元素
2: In if (after >= lengx) c(x, values) else c(x[1L:after], values,  :
  條件的長度 > 1,因此只能用其第一元素
3: In 1L:after : numerical expression has 2 elements: only the first used
4: In (after + 1L):lengx :
  numerical expression has 2 elements: only the first used

With the above code, only the first position is registered, with a warning message.

lapply(c(1,3), function(y) append(x, 'a', y))

yields this result:

[[1]]
[1] "1" "a" "2" "3"

[[2]]
[1] "1" "2" "3" "a"

Expected output:

1 a 2 3 a
Sati
  • 716
  • 6
  • 27
  • Another option: `s = split(x, cumsum(seq_along(x) %in% (pos+1))); unlist(rbind(s, "a"))` where `pos = c(1, 3)`. – Frank May 02 '18 at 16:48

1 Answers1

2

You can use `Reduce function:

x=1:10
pos=c(3,5,7,10)
Reduce(function(i,j)append(i,"a",j),cumsum(c(pos[1],diff(pos)+1)),init=x)
[1] "1"  "2"  "3"  "a"  "4"  "5"  "a"  "6"  "7"  "a"  "8"  "9"  "10" "a" 
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • The `cumsum` only works because the first element is 1. – James May 02 '18 at 16:50
  • @James I don't follow. You have an example? Oh, I think I see what you mean. Could edit to `Reduce(function(i,j)append(i,"a",j), pos + seq_along(pos) - 1,init=x)` where `pos = c(1,3)`, I think. – Frank May 02 '18 at 16:51
  • 1
    @Frank If the appends were after elements 2 and 3, the cumsum would be 2 and 5, but there would only be 4 elements at the point of the second insertion. Granted, `append` does actually append at the end when the after argument is after the length of the vector, but in a more complex example, this would lead to insertions in the wrong place. `after+seq_along(after)-1` gives the correct indicies. – James May 02 '18 at 16:55
  • Does this also mean that we can tweak the code to make it insert a value _before_ a certain position? For example, I might need to insert an "a" right in front, before position 1. – Sati May 03 '18 at 01:08
  • That willnot be appending but rather concatenating... i believe the position value in append is described as after and thus wont be an easy tweak to insert before...just kniw r doesnt have position 0 – Onyambu May 03 '18 at 14:18