How to create a data frame with dimension M x N in R

dataframe, r

Solution

Why not use a matrix? `data.frames` are for storing columns of varying types.

So,

m = 10
n = 5
mat = matrix(0, nrow = m, ncol = n)

If you really want a `data.frame`, coerce to one - the column names will simply be a default:

dat = as.data.frame(mat)
names(dat)
[1] "V1" "V2" "V3" "V4" "V5"

The problem with your approach is that you simply append the values one after the other, ignoring the dimensions you want. You can do it like this, but it's not a good idea to grow data, better to allocate it all upfront as above. Also, this results in a matrix anyway, which I think is what you should use.

WARNING: bad code ahead!

m <- 10 # nof row
n <- 5  # nof column

all <- NULL
for (i in 1:m) {
  row_i <- c(rep(0,n))
  all <- rbind(all,row_i)
}

Problem

Is there a way to do it? I'm stuck with this: ``` m <- 10 # nof row n <- 5 # nof column # We will fill each cell with '0' all <-c() for (i in 1:m) { row_i <- c(rep(0,n)) all <- c(all,row_i) } ``` Which only create 1 row as output.

Original source