I would like to construct a dataframe row-by-row in R. I’ve done some searching, and all I came up with is the suggestion to create an empty list, keep a list index scalar, then each time add to the list a single-row dataframe and advance the list index by one. Finally, do.call(rbind,) on the list.
While this works, it seems very cumbersome. Isn’t there an easier way for achieving the same goal?
Obviously I refer to cases where I can’t use some apply function and explicitly need to create the dataframe row by row. At least, is there a way to push into the end of a list instead of explicitly keeping track of the last index used?
You can grow them row by row by appending or using
rbind().That does not mean you should. Dynamically growing structures is one of the least efficient ways to code in R.
If you can, allocate your entire data.frame up front:
and then during your operations insert row at a time
That should work for arbitrary data.frame and be much more efficient. If you overshot N you can always shrink empty rows out at the end.