Create a data.frame with m columns and 2 rows

前端 未结 2 1049
逝去的感伤
逝去的感伤 2021-02-01 13:56

I would like to create a data.frame in R with m (a variable) number of columns (for example 30), and 2 rows and fill all the values in the data.frame initially with 0\'s. It see

2条回答
  •  孤城傲影
    2021-02-01 14:49

    For completeness:

    Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

    m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

    EDIT: speed test data.frame vs. as.data.frame

    system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
       user  system elapsed 
      8.005   0.108   8.165 
    
    system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
       user  system elapsed 
      3.759   0.048   3.802 
    

    Yes, it appears to be faster (by about 2 times).

提交回复
热议问题