I am writing R code to create a square matrix. So my approach is:
- Allocate a matrix of the correct size
- Loop through each element of my matrix and fill it with an appropriate value
My question is really simple: what is the best way to pre-allocate this matrix? Thus far, I have two ways:
> x <- matrix(data=NA,nrow=3,ncol=3)
> x
[,1] [,2] [,3]
[1,] NA NA NA
[2,] NA NA NA
[3,] NA NA NA
or
> x <- list()
> length(x) <- 3^2
> dim(x) <- c(3,3)
> x
[,1] [,2] [,3]
[1,] NULL NULL NULL
[2,] NULL NULL NULL
[3,] NULL NULL NULL
As far as I can see, the former is a more concise method than the latter. Also, the former fills the matrix with NAs, whereas the latter is filled with NULLs.
Which is the "better" way to do this? In this case, I'm defining "better" as "better performance", because this is statistical computing and this operation will be taking place with large datasets.
While the former is more concise, it isn't breathtakingly easier to understand, so I feel like this could go either way.
Also, what is the difference between NA and NULL in R? ?NA and ?NULL tell me that "NA" has a length of "1" whereas NULL has a length of "0" - but is there more here? Or a best practice? This will affect which method I use to create my matrix.