I'm trying to find most quick and effective way for appending to a vector. I tested 5 different appending methods and found that most quick method is just using preallocation (see append3 function):
# using generic combine
append1 <- function(n) {
v <- numeric()
for (i in 1:n) {
v <- c(v, i)
}
v
}
# using length and auto extending
append2 <- function(n) {
v <- numeric()
for (i in 1:n) {
v[length(v) + 1] <- i
}
v
}
# using preallocation
append3 <- function(n) {
v <- numeric(n)
for (i in 1:n) {
v[i] <- i
}
v
}
# using append
append4 <- function(n) {
v <- numeric()
for (i in 1:n) {
v <- append(v, i)
}
v
}
# using union
append5 <- function(n) {
v <- numeric()
for (i in 1:n) {
v <- union(v, i)
}
v
}
library(microbenchmark)
microbenchmark(append1(10000), append2(10000), append3(10000), append4(10000), append5(10000), times = 5)
# Unit: milliseconds
# expr min lq median uq max neval
# append1(10000) 338.77588 341.06664 342.66819 360.11682 413.78760 5
# append2(10000) 372.71939 373.20159 375.15096 385.76314 431.04495 5
# append3(10000) 23.26534 23.27922 23.59688 23.68247 24.80935 5
# append4(10000) 373.60041 373.91250 434.95227 435.57716 440.97028 5
# append5(10000) 6382.45524 6425.84974 6445.28719 6520.39599 6572.08553 5
But preallocation requires to know vector's initial capacity. I want to know is there another quick method that appends dynamically, without preallocation.