Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append value to empty vector in R?

I'm trying to learn R and I can't figure out how to append to a list.

If this were Python I would . . .

#Python
vector = []
values = ['a','b','c','d','e','f','g']

for i in range(0,len(values)):
    vector.append(values[i])

How do you do this in R?

#R Programming
> vector = c()
> values = c('a','b','c','d','e','f','g')
> for (i in 1:length(values))
+ #append value[i] to empty vector
like image 488
O.rka Avatar asked Sep 25 '22 15:09

O.rka


People also ask

How do I append a variable to a vector in R?

To append elements to a Vector in R, use the append() method. The append() is a built-in method that adds the various integer values into a Vector in the last position.

How do I create an empty list and add values in R?

To create an empty list in R, use the vector() function. The vector() function takes two arguments: mode and length. The mode is, in our case, is a list, and length is the number of elements in the list, and the list ends up actually empty, filled with NULL.

How do you declare an empty vector in R?

An empty vector can be created by simply not passing any value while creating a regular vector using the c() function. This will return NULL as an output. Example: R.


Video Answer


1 Answers

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

Here are several ways to append values to a vector. All of them are discouraged.

Appending to a vector in a loop

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Pre-allocate the vector before looping

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 
like image 249
Joshua Ulrich Avatar answered Oct 14 '22 05:10

Joshua Ulrich