Difference between as.data.frame(x) and data.frame(x)

前端 未结 6 1061
再見小時候
再見小時候 2020-12-24 01:44

What is the difference between as.data.frame(x) and data.frame(x)

In this following example, the result is the same at the exception of the columns names.

         


        
6条回答
  •  天涯浪人
    2020-12-24 02:14

    As you noted, the result does differ slightly, and this means that they are not exactly equal:

    identical(data.frame(x),as.data.frame(x))
    [1] FALSE
    

    So you might need to take care to be consistent in which one you use.

    But it is also worth noting that as.data.frame is faster:

    library(microbenchmark)
    microbenchmark(data.frame(x),as.data.frame(x))
    Unit: microseconds
                 expr    min     lq median      uq     max neval
        data.frame(x) 71.446 73.616  74.80 78.9445 146.442   100
     as.data.frame(x) 25.657 27.631  28.42 29.2100  93.155   100
    
    y <- matrix(1:1e6,1000,1000)
    microbenchmark(data.frame(y),as.data.frame(y))
    Unit: milliseconds
                 expr      min       lq   median       uq       max neval
        data.frame(y) 17.23943 19.63163 23.60193 41.07898 130.66005   100
     as.data.frame(y) 10.83469 12.56357 14.04929 34.68608  38.37435   100
    

提交回复
热议问题