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

Is there any way to do this?

I am stuck on 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 creates only 1 line as output.

+3
source share
2 answers

Why not use a matrix? data.framesare intended for storage of columns of various types.

So,

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

If you really want data.frameto force one thing - the column names will be just the default:

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

The problem with your approach is that you just add values ​​one by one, ignoring the dimensions you need. You can do it this way, but it is not a good idea for data growth, it is better to highlight everything as indicated above. Also, this still leads to the matrix, and I think this is what you should use.

: !

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)
}
+7

data.frame, .

as.data.frame(lapply(structure(.Data=1:N,.Names=1:N),function(x) numeric(M)))
+4

All Articles