Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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 of 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?

1 Answer

0 votes
by

To create an R data frame row-by-row, you can use the rbind() function to append new rows as follows:

N <- 5  

i =6

df <- data.frame(num=rep(0, N), txt=rep("a", N),

                 stringsAsFactors=FALSE)          #

df[i, ] <- list(1.4, "foo")

df

Output:

  num txt

1 0.0   a

2 0.0   a

3 0.0   a

4 0.0   a

5 0.0   a

6 1.4 foo

Browse Categories

...