在 R 中分配矩阵的最佳方法,NULL vs NA?
我正在编写 R 代码来创建方阵。所以我的方法是:
- 分配一个正确大小的矩阵
- 循环遍历矩阵的每个元素并用适当的值填充它
我的问题非常简单:预分配该矩阵的最佳方法是什么?到目前为止,我有两种方法:
> x <- matrix(data=NA,nrow=3,ncol=3)
> x
[,1] [,2] [,3]
[1,] NA NA NA
[2,] NA NA NA
[3,] NA NA NA
或
> 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
据我所知,前者是比后者更简洁的方法。此外,前者用 NA 填充矩阵,而后者用 NULL 填充。
哪种“更好”的方法可以做到这一点?在这种情况下,我将“更好”定义为“更好的性能”,因为这是统计计算,并且此操作将在大型数据集上进行。
虽然前者更简洁,但它并没有那么容易理解,所以我觉得这两种方式都可以。
另外,R中的NA和NULL有什么区别? ?NA 和 ?NULL 告诉我“NA”的长度为“1”,而 NULL 的长度为“0” - 但这里还有更多吗?或者最佳实践?这将影响我用来创建矩阵的方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如有疑问,请测试一下自己。第一种方法既简单又快捷。
关于NA和NULL的区别:
实际上有四个特殊的常量。
您可以在有关语言定义的 R 手册。
When in doubt, test yourself. The first approach is both easier and faster.
Regarding the difference between NA and NULL:
There are actually four special constants.
You can read more in the R manual on language definition.
根据这篇文章通过使用
NA_real_
进行预分配,我们可以比使用NA
进行预分配做得更好。来自文章:按照建议:让我们测试一下。
对于整数:
在我的测试用例中差异很小,但它确实存在。
According to this article we can do better than preallocating with
NA
by preallocating withNA_real_
. From the article:As recommended: let's test it.
And for integers:
The difference is small in my test cases, but it's there.