How to create an empty R vector to add new items How to create an empty R vector to add new items python python

How to create an empty R vector to add new items


vec <- vector()

See also vector help

?vector


I pre-allocate a vector with

> (a <- rep(NA, 10)) [1] NA NA NA NA NA NA NA NA NA NA

You can then use [] to insert values into it.


You can create an empty vector like so

vec <- numeric(0)

And then add elements using c()

vec <- c(vec, 1:5)

However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)