Create a data.frame with m columns and 2 rows

前端 未结 2 1050
逝去的感伤
逝去的感伤 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).

    0 讨论(0)
  • 2021-02-01 14:54

    Does m really need to be a data.frame() or will a matrix() suffice?

    m <- matrix(0, ncol = 30, nrow = 2)
    

    You can wrap a data.frame() around that if you need to:

    m <- data.frame(m)
    

    or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

    0 讨论(0)
提交回复
热议问题