Initializing data.frames()

R

R Problem Overview


Is there a quick way to initialize an empty data frame? If you know what the dimensions will be? For example:

Suppose I would like a blank data frame that has 100 rows and 10:

x <- data.frame(1:100,2,3,4,5,6,7,8,9,10) 
dim(x) ## that's right

But suppose I want something like 300 columns? How do I quickly initialize columns in a data.frame?

x <- data.frame(1:100,2,3,4,5 ....) ## *cries*

R Solutions


Solution 1 - R

> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300

Solution 2 - R

I always just convert a matrix:

x <- as.data.frame(matrix(nrow = 100, ncol = 10))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrandon BertelsenView Question on Stackoverflow
Solution 1 - RGavin SimpsonView Answer on Stackoverflow
Solution 2 - RMatt ParkerView Answer on Stackoverflow