參照與拷貝

R 的可擴展資料處理

Simon Urbanek

Member of R-Core, Lead Inventive Scientist, AT&T Labs Research

大矩陣與一般矩陣-相同點

  • 子集化
  • 指派
R 的可擴展資料處理

大矩陣與一般矩陣-差異

  • big.matrix 儲存在磁碟上
  • 可在 R 工作階段之間保留
  • 可在 R 工作階段之間共用
R 的可擴展資料處理

R 在指派時通常會建立拷貝

這會建立 a 的拷貝並指派給 b

a <- 42
b <- a
a
42
b
42
a <- 43
a
43
b
42
R 的可擴展資料處理

R 在指派時通常會建立拷貝

a <- 42

foo <- function(a){a <- 43 paste("Inside the function a is", a)}
foo(a)
"Inside the function a is 43"
paste("Outside the function a is still", a)
"Outside the function a is still 42"
R 的可擴展資料處理

不是所有 R 物件都會被拷貝

此函式會改變全域環境中 a 的值。

foo <- function(a) {a$val <- 43 
                    paste("Inside the function a is", a$val)}
a <- environment()
a$val <- 42
foo(a)
"Inside the function a is 43"
paste("Outside the function a$val is", a$val)
"Outside the function a$val is 43"
R 的可擴展資料處理

deepcopy()

# x 是一個 big matrix
x <- big.matrix(...)

# x_no_copy 與 x 指向同一個物件
x_no_copy <- x

# x_copy 與 x 指向不同物件
x_copy <- deepcopy(x)

R 的可擴展資料處理

參照行為

R 不會隱式建立拷貝

  • 降低記憶體用量
  • 減少執行時間
R 的可擴展資料處理

不是所有 R 物件都會被拷貝

library(bigmemory)

x <- big.matrix(nrow = 1, ncol = 3, type = "double", 
                init = 0, 
                backingfile = "hello-bigmemory.bin", 
                descriptorfile = "hello-bigmemory.desc")
R 的可擴展資料處理

不是所有 R 物件都會被拷貝

x_no_copy <- x
x[,]
0 0 0
x_no_copy[,]
0 0 0
x[,] <- 1
x[,]
1 1 1
x_no_copy[,]
1 1 1
R 的可擴展資料處理

不是所有 R 物件都會被拷貝

x_copy <- deepcopy(x)
x[,]
1 1 1
x_copy[,]
1 1 1
x[,] <- 2
x[,]
2 2 2
x_copy[,]
1 1 1
R 的可擴展資料處理

一起來練習吧!

R 的可擴展資料處理

Preparing Video For Download...