O.rka - 8 months ago 54

R Question

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

Answer

Here are several ways to do it. All of them are discouraged. 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".

```
# 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()`

.

Also note, as BrodieG pointed out in the comments: if you *absolutely must* use a for loop, then at least 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
```

Source (Stackoverflow)