在R中就地修改矩阵 [英] In place modification of matrices in R
问题描述
我有什么方法可以避免对R
中的矩阵进行原位修改吗?
I there any way to avoid copy-on-modify for in-place modifications of matrices in R
?
我正尝试将较小的矩阵复制到较大的矩阵的切片,如下所示.
I am trying to copy a smaller matrix to a slice of larger matrix as follows.
library(data.table)
y <- matrix(c(11,21,31,12,22,32),nrow=3,ncol=2)
address(y)
[1] "08429190"
y[2:3,] <- matrix(c(1,1,8,12),nrow=2)
address(y)
[1] "0E033D28"
推荐答案
使用在Windows 8.1上的RStudio 0.99.441中运行的R 3.2.0,并使用pryr::address
,我得到的操作与OP相同.问题是RStudio的环境"窗格对y进行了引用.通常, Hadley Wickham 对此都有很好的说明.
I get the same behaviour as the OP using R 3.2.0 running within RStudio 0.99.441 on Windows 8.1 and using pryr::address
. The issue is RStudio has a reference to y for its Environment pane. As often the case, Hadley Wickham has some excellent documentation of this.
除了不使用RStudio之外,对于全球环境中的矩阵,我认为没有其他方法可以解决此问题.我已经尝试了其他几件事.函数中的矩阵很好:
I don't think there's any way around this for matrices in the global environment other than not using RStudio. I've tried a couple of other things. Matrices within a function are fine:
library("pryr")
fn <- function() {
y <- matrix(c(11,21,31,12,22,32),nrow=3,ncol=2)
print(address(y))
y[2:3,] <- matrix(c(1,1,8,12),nrow=2)
print(address(y))
}
呼叫fn()
应该显示地址不变.
Calling fn()
should show that the address is unchanged.
但是,将y创建为全局环境中的列表或环境的成员并不会阻止写入时的复制(例如x <- new.env(); x$y <- matrix(...)
).
However, creating y as a member of a list or environment which are in the global environment doesn't prevent the copy on write (e.g. x <- new.env(); x$y <- matrix(...)
).
每>是否有任何方法可以禁用环境窗格在RStudio中?似乎没有任何方法可以禁用环境窗格.
Per Is there any way to disable environment pane in RStudio? there doesn't seem to be any way of disabling the environment pane.
data.table
仍然设法避免不必要的复制.试试:
data.table
still manages to avoid unncessarily copies. Try:
library("data.table")
x <- as.data.table(matrix(c(11,21,31,12,22,32),nrow=3,ncol=2))
address(x)
x[2:3, `:=`(V1 = c(1, 1), V2 = c(8, 12))]
address(x)
x[, V3 := V1 + V2]
address(x)
这篇关于在R中就地修改矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!