参照とコピー

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 is a big matrix
x <- big.matrix(...)

# x_no_copy and x refer to the same object
x_no_copy <- x

# x_copy and x refer to different objects
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...