append

append(x, values, after=length(x))
Append values to x, possibly inserted into the middle of x. This function is important since it tends to perform a little faster than using the concatenation (c) function.
  • x – A vector.
  • y – Another vector to place at the end of or within x.
  • after – Where values should go in x, by default at the end.

Example. Concatenation (c) is pretty fast, but append is even faster and therefor preferable when concatenating just two vectors, which is shown in an instance below using the system.time function. It is worth noting that the impact is small and often negligible for shorter vectors when either c or append is called just once, but the impact becomes very meaningful in the context of repeated calls, e.g. in a loop.
> x      <- 1:10^6
> values <- rnorm(10^5)
> length(x)
[1] 1000000
> 
> system.time(y1 <- c(x, values))
   user  system elapsed 
  0.004   0.000   0.004 
> 
> system.time(y2 <- append(x, values))
   user  system elapsed 
  0.003   0.000   0.003 
> 
> identical(y1, y2)
[1] TRUE
> 
> 
> x <- 1:10
> append(x, pi)
 [1]  1.000000  2.000000  3.000000  4.000000
 [5]  5.000000  6.000000  7.000000  8.000000
 [9]  9.000000 10.000000  3.141593
> 
> append(x, pi, after=5)
 [1]  1.000000  2.000000  3.000000  4.000000
 [5]  5.000000  3.141593  6.000000  7.000000
 [9]  8.000000  9.000000 10.000000
Other functions used in the example: system.time, identical.

Leave a Reply