修改列表和环境
Modifying lists and environments
我正在阅读有关环境的 Hadley Wickham 高级 R。 Here 它提到:
Unlike most objects in R, when you modify an environment, it does not
make a copy. For example, look at this modify() function.
modify <- function(x) {
x$a <- 2
invisible()
}
If you apply it to a list, the original list is not changed because
modifying a list actually creates and modifies a copy.
x_l <- list()
x_l$a <- 1
modify(x_l)
x_l$a
## [1] 1
However, if you apply it to an environment, the original environment
is modified:
x_e <- new.env()
x_e$a <- 1
modify(x_e)
x_e$a
## [1] 2
修改列表创建和修改副本是什么意思?我看到在应用 modify(x_l)
之后,我会假设 x_l
指向的对象已被修改。但是,它没有(x_l$a
仍然是 1)。修改功能未更新列表的幕后情况是什么?
如果列表被修改,则会创建一个新列表(并且在函数中创建的对象是该函数的本地对象,并在函数退出时被删除)。请注意下面涉及L1
的计算,并且L1
的地址在修改后发生了变化。
另一方面,环境具有与其内容截然不同的身份。更改环境的内容不会更改环境的标识。注意我们修改了环境的内容后e1
它的地址没有变。
library(pryr)
L1 <- list(a = 1)
address(L1)
## [1] "0xdb8aeb0"
L1$b <- 2
address(L1)
## [1] "0x841eca8"
e1 <- list2env(L1)
address(e1)
## [1] "0xbdf2420"
e1$c <- 3
address(e1)
## [1] "0xbdf2420"
我正在阅读有关环境的 Hadley Wickham 高级 R。 Here 它提到:
Unlike most objects in R, when you modify an environment, it does not make a copy. For example, look at this modify() function.
modify <- function(x) {
x$a <- 2
invisible()
}
If you apply it to a list, the original list is not changed because modifying a list actually creates and modifies a copy.
x_l <- list()
x_l$a <- 1
modify(x_l)
x_l$a
## [1] 1
However, if you apply it to an environment, the original environment is modified:
x_e <- new.env()
x_e$a <- 1
modify(x_e)
x_e$a
## [1] 2
修改列表创建和修改副本是什么意思?我看到在应用 modify(x_l)
之后,我会假设 x_l
指向的对象已被修改。但是,它没有(x_l$a
仍然是 1)。修改功能未更新列表的幕后情况是什么?
如果列表被修改,则会创建一个新列表(并且在函数中创建的对象是该函数的本地对象,并在函数退出时被删除)。请注意下面涉及L1
的计算,并且L1
的地址在修改后发生了变化。
另一方面,环境具有与其内容截然不同的身份。更改环境的内容不会更改环境的标识。注意我们修改了环境的内容后e1
它的地址没有变。
library(pryr)
L1 <- list(a = 1)
address(L1)
## [1] "0xdb8aeb0"
L1$b <- 2
address(L1)
## [1] "0x841eca8"
e1 <- list2env(L1)
address(e1)
## [1] "0xbdf2420"
e1$c <- 3
address(e1)
## [1] "0xbdf2420"