考虑一个整数数组
> a <- 1:12
> tracemem(a)
设置dim
属性不会复制对象
> dim(a) <- c(3, 2, 2)
> a
, , 1
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
, , 2
[,1] [,2]
[1,] 7 10
[2,] 8 11
[3,] 9 12
> dim(a) <- c(dim(a)[1L], prod(dim(a)[-1L]))
> a
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
但是如果在函数中设置属性会怎么样?
> f <- function(x) { dim(x) <- c(dim(x)[1L], prod(dim(x)[-1L])); x}
> dim(a) <- c(3, 2, 2)
> f(a)
tracemem[0xb99678 -> 0x1b7aac30]: f
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
现在它已经复制了。我理解a
和f(a)
是不同的对象,
但是这些对象是指向相同的数据,还是数据也是如此
复制?
答案 0 :(得分:0)
object_size
包中pryr
的输出表明数据
被复制。
> object_size(list(a))
304 B
> object_size(list(a, a))
312 B
> object_size(list(a, a, a))
328 B
> b <- f(a)
tracemem[0x1fa7660 -> 0xbadae8]: f
> object_size(list(a, b))
504 B
>