Ibe Ibe - 9 days ago 5
R Question

Append data frames together in a for loop

I have a

for loop
which produces a data frame after each iteration. I want to append all data frames together but finding it difficult. Following is what I
am trying, please suggest how to fix it:

d = NULL
for (i in 1:7){

# vector output
model <- #some processing

# add vector to a dataframe
df <- data.frame(model)

}

df_total <- rbind(d,df)

Answer

Don't do it inside the loop. Make a list, then combine them outside the loop.

datalist = list()

for (i in 1:5) {
    # ... make some data
    dat <- data.frame(x = rnorm(10), y = runif(10))
    dat$i <- i  # maybe you want to keep track of which iteration produced it?
    datalist[[i]] <- dat # add it to your list
}

big_data = do.call(rbind, datalist)
# or big_data <- dplyr::bind_rows(datalist)
# or big_data <- data.table::rbindlist(datalist)

This is a much more R-like way to do things. It can also be substantially faster, especially if you use dplyr::bind_rows or data.table::rbindlist for the final combining of data frames.

Comments