Я пишу пакет, в котором мне нужно изменить большой список с помощью ряда функций. Каковы возможные способы достижения этого?
Я прилагаю свою реализацию, но не уверен, что это оптимально.
##' @export
test <- function(param = TRUE){
x <- list("a"= data.frame(a1 = c(1,2), a2 = c(1,1)),
"b"= data.frame(b1 = c(2,3), b2 = c(1,2)))
message(paste("in test() function, references to x[[1]]:", inspect(x)[["children"]][[1]][["address"]]))
message(paste("in test() function, references to x[[2]]:", inspect(x)[["children"]][[2]][["address"]]))
for(name in names(x)) updateList(x, name)
message(paste("in test() function, post update references to x[[1]]:", inspect(x)[["children"]][[1]][["address"]]))
message(paste("in test() function, post update references to x[[2]]:", inspect(x)[["children"]][[2]][["address"]]))
x
}
updateList <- function(x, name){
message(paste("updateList() references to x[[1]]:", inspect(x)[["children"]][[1]][["address"]]))
message(paste("updateList() references to x[[2]]:", inspect(x)[["children"]][[2]][["address"]]))
newdf <- rbind(x[[name]], c(4,4))
assign("temp", newdf, envir = parent.frame(n = 1))
with(parent.frame(n = 1), x[[name]] <- temp)
invisible(NULL)
}
В Console
, когда я запускаю test()
> library(pryr)
> test()
in test() function, references to x[[1]]: 0x55d66ce9dd98
in test() function, references to x[[2]]: 0x55d670954508
updateList() references to x[[1]]: 0x55d66ce9dd98
updateList() references to x[[2]]: 0x55d670954508
updateList() references to x[[1]]: 0x55d66fca1688
updateList() references to x[[2]]: 0x55d670954508
in test() function, post update references to x[[1]]: 0x55d66fca1688
in test() function, post update references to x[[2]]: 0x55d66ffb8208
$a
a1 a2
1 1 1
2 2 1
3 4 4
$b
b1 b2
1 2 1
2 3 2
3 4 4
Есть ли способ убедиться, что R не копирует? Как узнать, что он создал промежуточные копии?
Как подсказывает @ len-greski, мы можем видеть адрес каждого элемента. Мы видим, что на каждой итерации копируется только один фрейм данных и остальные не.