0

I would like to create an empty dataframe and therefore perform a loop and add the new content to a (new) dataframe.

Therefore I wrote something like this:

number <- c(1,2)
text <- c("Yes", "No")
df_test <- data.frame(number, text)

df_base = data.frame(number = numeric(), text = character())

for(i in 1:nrow(df_test)){

 text <- df_test$text[i]
 number <- df_test$number[i]

 df_temp <- data.frame(text, number)
 df_base <- rbind(df_base, df_temp) 

}

Code above does the trick but does not seem to be the most efficient way. Any thoughts on how I can write this better?

Frits Verstraten
  • 2,049
  • 7
  • 22
  • 41
  • 1
    You should never create a data frame row by row in R ([see here](http://stackoverflow.com/questions/3642535/creating-an-r-dataframe-row-by-row)). In this case, why not just do `df_base <- df_test`? – David Robinson Jun 05 '16 at 15:47
  • This is just an example case....Just for reproduction purposes – Frits Verstraten Jun 05 '16 at 15:54
  • If your goal is to change text or number columns in the new table, know that it's also usually more efficient to find a [vectorized](http://www.noamross.net/blog/2014/4/16/vectorization-in-r--why.html) solution – David Robinson Jun 05 '16 at 16:42

1 Answers1

0

If you know the final size of your data.frame (df_base), you could pre-allocate the object:

df_base <- data.frame(text=character(nrow(df_test)),
                      number=numeric(nrow(dr_test)))

Then, in the loop, fill in these columns:

for(i in 1:nrow(df_test)){

  text <- df_test$text[i]
  number <- df_test$number[i]

  df_base[i,"text"] <- text
  df_base[i,"number"] <- number

}

This will save R from making multiple copies of df_base as it rbinds in each loop.

lmo
  • 37,904
  • 9
  • 56
  • 69