Best way to allocate matrix in R, NULL vs NA?

后端 未结 3 1337
深忆病人
深忆病人 2020-12-24 11:31

I am writing R code to create a square matrix. So my approach is:

  1. Allocate a matrix of the correct size
  2. Loop through each element of my matrix and fil
3条回答
  •  一向
    一向 (楼主)
    2020-12-24 12:21

    When in doubt, test yourself. The first approach is both easier and faster.

    > create.matrix <- function(size) {
    + x <- matrix()
    + length(x) <- size^2
    + dim(x) <- c(size,size)
    + x
    + }
    > 
    > system.time(x <- matrix(data=NA,nrow=10000,ncol=10000))
       user  system elapsed 
       4.59    0.23    4.84 
    > system.time(y <- create.matrix(size=10000))
       user  system elapsed 
       0.59    0.97   15.81 
    > identical(x,y)
    [1] TRUE
    

    Regarding the difference between NA and NULL:

    There are actually four special constants.

    In addition, there are four special constants, NULL, NA, Inf, and NaN.

    NULL is used to indicate the empty object. NA is used for absent (“Not Available”) data values. Inf denotes infinity and NaN is not-a-number in the IEEE floating point calculus (results of the operations respectively 1/0 and 0/0, for instance).

    You can read more in the R manual on language definition.

提交回复
热议问题