SlideShare a Scribd company logo
1 of 18
Download to read offline
HIRO: R Advent Calendar 2014
 R Advent Calendar 2014 14日目の記事です
 R6の解説そのまま使わせて頂きました
http://cran.r-project.org/web/packages/R6のVignettes
http://stackoverflow.com/questions/tagged/r6
 なぜ今更 R6 Classes?
 JapanR 2014で「すごく使いやすい」と聞
いたから
 S4, R5が使いにくかったから(個人の意見です)
 記事にするネタが無くて困っていたから…
HIRO: R Advent Calendar 2014
HIRO: R Advent Calendar 2014
 他言語のようなオブジェクト指向
 R6パッケージを読み込む
 特徴
 参照セマンティクス
 active bindings
 public/private メソッド
 継承(スーパークラスとサブクラス)
HIRO: R Advent Calendar 2014
library(R6)
Person <- R6Class("Person",
public = list(
name = NA,
hair = NA,
initialize = function(name, hair) {
if (!missing(name)) self$name <- name
if (!missing(hair)) self$hair <- hair
self$greet()
},
set_hair = function(val) {
self$hair <- val
},
greet = function() {
cat(paste0("Hello, my name is ", self$name, ".¥n"))
}
)
)
Person classを定義する
フィールド
メソッド
コンストラクタ
publicメンバは
selfを使って呼
び出す
HIRO: R Advent Calendar 2014
ann <- Person$new("Ann", "black")
> Hello, my name is Ann.
ann
> <Person>
> Public:
> greet: function
> hair: black
> initialize: function
> name: Ann
> set_hair: function
Person classのインスタンス化
ann$hair
> black
ann$set_hair <- “red”
#または
ann$hair <- “red”
ann$hair
> red
publicメンバへのアクセス
HIRO: R Advent Calendar 2014
Numbers <- R6Class("Numbers",
public = list(
x = 100
),
active = list(
x2 = function(value) {
if (missing(value)) return(self$x * 2)
else self$x <- value/2
},
rand = function() rnorm(1)
)
)
Number classの定義 publicメンバへのアクセス
n <- Numbers$new()
n$x
> [1] 100
n$rand
#> [1] 0.2648
n$rand
#> [1] 2.171
n$rand <- 3
#> Error: unused argument
(quote(3))
active bindingsへのアクセス
active bindings: アクセスされる
たびに実行される
HIRO: R Advent Calendar 2014
Queue <- R6Class("Queue",
public = list(
initialize = function(...) {
for (item in list(...)) {
self$push(item)
}
},
push = function(x) {
private$queue <- c(private$queue, list(x))
invisible(self)
},
pop = function() {
if (private$length() == 0) return(NULL)
# Can use private$queue for explicit access
head <- private$queue[[1]]
private$queue <- private$queue[-1]
head
}
),
private = list(
queue = list(),
length = function() base::length(private$queue)
)
)
今度の例はprivateメンバを含むクラス
push(“something”)の度にキューが伸びる
pop()で最初に入ったものから1つずつ取り
除かれる
HIRO: R Advent Calendar 2014
q <- Queue$new(5, 6, "foo")
q$push("something")
q$push("another thing")
#q$push("something")$push("another thing"))でも同じ結果
q$pop()
> [1] 5
q$queue
> NULL
q$length()
> Error: attempt to apply non-function
Queue classのインスタンス化
チェーンも可
publicメンバにはアクセス可能
privateメンバにはアクセスできない
HIRO: R Advent Calendar 2014
q <- Queue$new(5, 6, "foo")
q$push("something")
q$push("another thing")
q$push(17)
#q$push("something")$push("another thing")$push(17)
#でも同じ結果
q$pop()
> [1] 5
q$pop()
> [1] 6
Queue classのインスタンス化
HIRO: R Advent Calendar 2014
HistoryQueue <- R6Class("HistoryQueue",
inherit = Queue,
public = list(
show = function() {
cat("Next item is at index", private$head_idx + 1,
"¥n")
for (i in seq_along(private$queue)) {
cat(i, ": ", private$queue[[i]], "¥n", sep = "")
}
},
pop = function() {
if (private$length() - private$head_idx == 0)
return(NULL)
private$head_idx <<- private$head_idx + 1
private$queue[[private$head_idx]]
}
),
private = list(
head_idx = 0
)
)
Queue classの継承
show() の追加
method() のオーバーライド
HIRO: R Advent Calendar 2014
hq <- HistoryQueue$new(5, 6, "foo")
hq$show()
> Next item is at index 1
> 1: 5
> 2: 6
> 3: foo
hq$pop()
> [1] 5
hq$show()
> Next item is at index 2
> 1: 5
> 2: 6
> 3: foo
hq$pop()
> [1] 6
Queueのサブクラスである
HistoryQueueのインスタンス化
HIRO: R Advent Calendar 2014
CountingQueue <- R6Class("CountingQueue",
inherit = Queue,
public = list(
push = function(x) {
private$total <<- private$total + 1
super$push(x)
},
get_total = function() private$total
),
private = list(
total = 0
)
)
cq <- CountingQueue$new("x", "y")
cq$get_total()
> [1] 2
cq$push("z")
cq$pop()
> [1] "x"
cq$pop()
> [1] "y"
cq$get_total()
> [1] 3
Queue classの継承
スーパークラスのメソッドをsuper$で呼び出し
HIRO: R Advent Calendar 2014
SimpleClass <- R6Class("SimpleClass",
public = list(x = NULL)
)
NonSharedField <- R6Class("NonSharedField",
public = list(
e = NULL,
initialize = function() e <<- SimpleClass$new()
)
)
n1 <- NonSharedField$new()
n1$e$x <- 1
n2 <- NonSharedField$new()
n2$e$x <- 2
# n2$e$x does not affect n1$e$x
n1$e$x
> [1] 1
initializeメソッドの中で
オブジェクト参照
*initializeメソッドの中ではなく
直接設定される場合、すべてで共有
されてしまう(左の例の場合、
n1$e$x = 2 となる)
HIRO: R Advent Calendar 2014
NP <- R6Class("NP",
portable = FALSE,
public = list(
x = NA,
getx = function() x,
setx = function(value) x <<- value
)
)
np <- NP$new()
np$setx(10)
np$getx()
> [1] 10
P <- R6Class("P",
portable = TRUE, # This is default
public = list(
x = NA,
getx = function() self$x,
setx = function(value) self$x <- value
)
)
p <- P$new()
p$setx(10)
p$getx()
> [1] 10
non-portable classの場合のみ
selfの代わりに <<- 使用可
Portable class: portable=TRUE
・異なるパッケージ間でも継承
・メンバへのアクセスには、(public) self$x もしくは <<- や private$y が必要
HIRO: R Advent Calendar 2014
clsTrnR6 <- R6Class("clsTrnR6",
lock=FALSE,
public = list(
x = NA,
initialize = function(x) {
self$x <- x
},
push_function = function(name, meth) {
self[[name]] <- meth
environment(self[[name]]) <-
environment(self$push_function)
}
)
)
clsR6 <- clsTrnR6$new(x=4)
clsR6$x
#[1] 4
clsR6$push_function("predict", function(y) y*self$x)
clsR6$predict(11)
メソッドの追加
HIRO: R Advent Calendar 2014
lock = FALSE
A <- R6Class("A", public = list(
initialize = function() {
reg.finalizer(self,
function(e) print("Finalizer has been called!"),
onexit = TRUE)
}
))
A$new()
1+1
invisible(gc()
> "Finalizer has been called!"
initializeの中で
ファイナライザを呼び出し
最後の処理の結果が.Last.valueに入るので
何か別の処理をする
gc()で終了
HIRO: R Advent Calendar 2014
 ありがとうございました m(_ _)m
 誤訳・誤解等ご指摘ください
 あっても大目に見て下さい…
HIRO: R Advent Calendar 2014

More Related Content

What's hot

EucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみました
EucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみましたEucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみました
EucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみましたEtsuji Nakai
 
入門機械学習1,2章
入門機械学習1,2章入門機械学習1,2章
入門機械学習1,2章Kazufumi Ohkawa
 
RailsエンジニアのためのSQLチューニング速習会
RailsエンジニアのためのSQLチューニング速習会RailsエンジニアのためのSQLチューニング速習会
RailsエンジニアのためのSQLチューニング速習会Nao Minami
 
Rユーザのためのspark入門
Rユーザのためのspark入門Rユーザのためのspark入門
Rユーザのためのspark入門Shintaro Fukushima
 
データサイエンティスト必見!M-1グランプリ
データサイエンティスト必見!M-1グランプリデータサイエンティスト必見!M-1グランプリ
データサイエンティスト必見!M-1グランプリSatoshi Kitajima
 
LastaFluteでKotlinをはじめよう
LastaFluteでKotlinをはじめようLastaFluteでKotlinをはじめよう
LastaFluteでKotlinをはじめようShinsuke Sugaya
 
Data processing at spotify using scio
Data processing at spotify using scioData processing at spotify using scio
Data processing at spotify using scioJulien Tournay
 
PHP Object Injection入門
PHP Object Injection入門PHP Object Injection入門
PHP Object Injection入門Yu Iwama
 
Rで触れる日本経済~RでVAR編~
Rで触れる日本経済~RでVAR編~Rで触れる日本経済~RでVAR編~
Rで触れる日本経済~RでVAR編~Kazuya Wada
 
2013-12-08 西区プログラム勉強会
2013-12-08 西区プログラム勉強会2013-12-08 西区プログラム勉強会
2013-12-08 西区プログラム勉強会Takatoshi Murakami
 
Why dont you_create_new_spark_jl
Why dont you_create_new_spark_jlWhy dont you_create_new_spark_jl
Why dont you_create_new_spark_jlShintaro Fukushima
 
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと 12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと Haruka Ozaki
 
PythonでテキストをJSONにした話(PyCon mini sapporo 2015)
PythonでテキストをJSONにした話(PyCon mini sapporo 2015)PythonでテキストをJSONにした話(PyCon mini sapporo 2015)
PythonでテキストをJSONにした話(PyCon mini sapporo 2015)Satoshi Yamada
 

What's hot (18)

EucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみました
EucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみましたEucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみました
EucalyptusのHadoopクラスタとJaqlでBasket解析をしてHiveとの違いを味わってみました
 
入門機械学習1,2章
入門機械学習1,2章入門機械学習1,2章
入門機械学習1,2章
 
20140920 tokyo r43
20140920 tokyo r4320140920 tokyo r43
20140920 tokyo r43
 
RailsエンジニアのためのSQLチューニング速習会
RailsエンジニアのためのSQLチューニング速習会RailsエンジニアのためのSQLチューニング速習会
RailsエンジニアのためのSQLチューニング速習会
 
Rユーザのためのspark入門
Rユーザのためのspark入門Rユーザのためのspark入門
Rユーザのためのspark入門
 
データサイエンティスト必見!M-1グランプリ
データサイエンティスト必見!M-1グランプリデータサイエンティスト必見!M-1グランプリ
データサイエンティスト必見!M-1グランプリ
 
R -> Python
R -> PythonR -> Python
R -> Python
 
LastaFluteでKotlinをはじめよう
LastaFluteでKotlinをはじめようLastaFluteでKotlinをはじめよう
LastaFluteでKotlinをはじめよう
 
Data processing at spotify using scio
Data processing at spotify using scioData processing at spotify using scio
Data processing at spotify using scio
 
PHP Object Injection入門
PHP Object Injection入門PHP Object Injection入門
PHP Object Injection入門
 
Rで触れる日本経済~RでVAR編~
Rで触れる日本経済~RでVAR編~Rで触れる日本経済~RでVAR編~
Rで触れる日本経済~RでVAR編~
 
2013-12-08 西区プログラム勉強会
2013-12-08 西区プログラム勉強会2013-12-08 西区プログラム勉強会
2013-12-08 西区プログラム勉強会
 
Tokyor36
Tokyor36Tokyor36
Tokyor36
 
Why dont you_create_new_spark_jl
Why dont you_create_new_spark_jlWhy dont you_create_new_spark_jl
Why dont you_create_new_spark_jl
 
Haskell で CLI
Haskell で CLIHaskell で CLI
Haskell で CLI
 
MapReduce入門
MapReduce入門MapReduce入門
MapReduce入門
 
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと 12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
12-11-30 Kashiwa.R #5 初めてのR Rを始める前に知っておきたい10のこと
 
PythonでテキストをJSONにした話(PyCon mini sapporo 2015)
PythonでテキストをJSONにした話(PyCon mini sapporo 2015)PythonでテキストをJSONにした話(PyCon mini sapporo 2015)
PythonでテキストをJSONにした話(PyCon mini sapporo 2015)
 

Viewers also liked

Kobe.R #15 - Incanter チョットシッテル
Kobe.R #15 - Incanter チョットシッテルKobe.R #15 - Incanter チョットシッテル
Kobe.R #15 - Incanter チョットシッテルtnoda
 
Factor型の注意点
Factor型の注意点Factor型の注意点
Factor型の注意点Hiroki K
 
サポートベクトルマシン入門
サポートベクトルマシン入門サポートベクトルマシン入門
サポートベクトルマシン入門Wakamatz
 
Mad kobe.r14
Mad kobe.r14Mad kobe.r14
Mad kobe.r14florets1
 
Packages for data wrangling データ前処理のためのパッケージ
Packages for data wrangling データ前処理のためのパッケージPackages for data wrangling データ前処理のためのパッケージ
Packages for data wrangling データ前処理のためのパッケージHiroki K
 
Rデータ処理入門
Rデータ処理入門Rデータ処理入門
Rデータ処理入門Hiroki K
 
Kobe.R #18: 本の紹介: 通称「緑本」
Kobe.R #18: 本の紹介: 通称「緑本」Kobe.R #18: 本の紹介: 通称「緑本」
Kobe.R #18: 本の紹介: 通称「緑本」tnoda
 
Shibuya.lisp #28: 仮題: R について
Shibuya.lisp #28: 仮題: R についてShibuya.lisp #28: 仮題: R について
Shibuya.lisp #28: 仮題: R についてtnoda
 
ggplot2再入門(2015年バージョン)
ggplot2再入門(2015年バージョン)ggplot2再入門(2015年バージョン)
ggplot2再入門(2015年バージョン)yutannihilation
 

Viewers also liked (11)

Kobe.R #15 - Incanter チョットシッテル
Kobe.R #15 - Incanter チョットシッテルKobe.R #15 - Incanter チョットシッテル
Kobe.R #15 - Incanter チョットシッテル
 
Factor型の注意点
Factor型の注意点Factor型の注意点
Factor型の注意点
 
サポートベクトルマシン入門
サポートベクトルマシン入門サポートベクトルマシン入門
サポートベクトルマシン入門
 
Mad kobe.r14
Mad kobe.r14Mad kobe.r14
Mad kobe.r14
 
R in life science
R in life scienceR in life science
R in life science
 
Packages for data wrangling データ前処理のためのパッケージ
Packages for data wrangling データ前処理のためのパッケージPackages for data wrangling データ前処理のためのパッケージ
Packages for data wrangling データ前処理のためのパッケージ
 
Rデータ処理入門
Rデータ処理入門Rデータ処理入門
Rデータ処理入門
 
Kobe.R #18: 本の紹介: 通称「緑本」
Kobe.R #18: 本の紹介: 通称「緑本」Kobe.R #18: 本の紹介: 通称「緑本」
Kobe.R #18: 本の紹介: 通称「緑本」
 
R in life science2
R in life science2R in life science2
R in life science2
 
Shibuya.lisp #28: 仮題: R について
Shibuya.lisp #28: 仮題: R についてShibuya.lisp #28: 仮題: R について
Shibuya.lisp #28: 仮題: R について
 
ggplot2再入門(2015年バージョン)
ggplot2再入門(2015年バージョン)ggplot2再入門(2015年バージョン)
ggplot2再入門(2015年バージョン)
 

Recently uploaded

論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...Toru Tamaki
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムsugiuralab
 
TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdftaisei2219
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Danieldanielhu54
 
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)Hiroki Ichikura
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Yuma Ohgami
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略Ryo Sasaki
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A surveyToru Tamaki
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものですiPride Co., Ltd.
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNetToru Tamaki
 

Recently uploaded (10)

論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
論文紹介:Content-Aware Token Sharing for Efficient Semantic Segmentation With Vis...
 
スマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システムスマートフォンを用いた新生児あやし動作の教示システム
スマートフォンを用いた新生児あやし動作の教示システム
 
TSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdfTSAL operation mechanism and circuit diagram.pdf
TSAL operation mechanism and circuit diagram.pdf
 
Postman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By DanielPostman LT Fukuoka_Quick Prototype_By Daniel
Postman LT Fukuoka_Quick Prototype_By Daniel
 
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
【早稲田AI研究会 講義資料】3DスキャンとTextTo3Dのツールを知ろう!(Vol.1)
 
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
Open Source UN-Conference 2024 Kawagoe - 独自OS「DaisyOS GB」の紹介
 
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
[DevOpsDays Tokyo 2024] 〜デジタルとアナログのはざまに〜 スマートビルディング爆速開発を支える 自動化テスト戦略
 
論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey論文紹介:Semantic segmentation using Vision Transformers: A survey
論文紹介:Semantic segmentation using Vision Transformers: A survey
 
SOPを理解する 2024/04/19 の勉強会で発表されたものです
SOPを理解する       2024/04/19 の勉強会で発表されたものですSOPを理解する       2024/04/19 の勉強会で発表されたものです
SOPを理解する 2024/04/19 の勉強会で発表されたものです
 
論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet論文紹介:Automated Classification of Model Errors on ImageNet
論文紹介:Automated Classification of Model Errors on ImageNet
 

R6 classes

  • 1. HIRO: R Advent Calendar 2014
  • 2.  R Advent Calendar 2014 14日目の記事です  R6の解説そのまま使わせて頂きました http://cran.r-project.org/web/packages/R6のVignettes http://stackoverflow.com/questions/tagged/r6  なぜ今更 R6 Classes?  JapanR 2014で「すごく使いやすい」と聞 いたから  S4, R5が使いにくかったから(個人の意見です)  記事にするネタが無くて困っていたから… HIRO: R Advent Calendar 2014
  • 3. HIRO: R Advent Calendar 2014
  • 4.  他言語のようなオブジェクト指向  R6パッケージを読み込む  特徴  参照セマンティクス  active bindings  public/private メソッド  継承(スーパークラスとサブクラス) HIRO: R Advent Calendar 2014
  • 5. library(R6) Person <- R6Class("Person", public = list( name = NA, hair = NA, initialize = function(name, hair) { if (!missing(name)) self$name <- name if (!missing(hair)) self$hair <- hair self$greet() }, set_hair = function(val) { self$hair <- val }, greet = function() { cat(paste0("Hello, my name is ", self$name, ".¥n")) } ) ) Person classを定義する フィールド メソッド コンストラクタ publicメンバは selfを使って呼 び出す HIRO: R Advent Calendar 2014
  • 6. ann <- Person$new("Ann", "black") > Hello, my name is Ann. ann > <Person> > Public: > greet: function > hair: black > initialize: function > name: Ann > set_hair: function Person classのインスタンス化 ann$hair > black ann$set_hair <- “red” #または ann$hair <- “red” ann$hair > red publicメンバへのアクセス HIRO: R Advent Calendar 2014
  • 7. Numbers <- R6Class("Numbers", public = list( x = 100 ), active = list( x2 = function(value) { if (missing(value)) return(self$x * 2) else self$x <- value/2 }, rand = function() rnorm(1) ) ) Number classの定義 publicメンバへのアクセス n <- Numbers$new() n$x > [1] 100 n$rand #> [1] 0.2648 n$rand #> [1] 2.171 n$rand <- 3 #> Error: unused argument (quote(3)) active bindingsへのアクセス active bindings: アクセスされる たびに実行される HIRO: R Advent Calendar 2014
  • 8. Queue <- R6Class("Queue", public = list( initialize = function(...) { for (item in list(...)) { self$push(item) } }, push = function(x) { private$queue <- c(private$queue, list(x)) invisible(self) }, pop = function() { if (private$length() == 0) return(NULL) # Can use private$queue for explicit access head <- private$queue[[1]] private$queue <- private$queue[-1] head } ), private = list( queue = list(), length = function() base::length(private$queue) ) ) 今度の例はprivateメンバを含むクラス push(“something”)の度にキューが伸びる pop()で最初に入ったものから1つずつ取り 除かれる HIRO: R Advent Calendar 2014
  • 9. q <- Queue$new(5, 6, "foo") q$push("something") q$push("another thing") #q$push("something")$push("another thing"))でも同じ結果 q$pop() > [1] 5 q$queue > NULL q$length() > Error: attempt to apply non-function Queue classのインスタンス化 チェーンも可 publicメンバにはアクセス可能 privateメンバにはアクセスできない HIRO: R Advent Calendar 2014
  • 10. q <- Queue$new(5, 6, "foo") q$push("something") q$push("another thing") q$push(17) #q$push("something")$push("another thing")$push(17) #でも同じ結果 q$pop() > [1] 5 q$pop() > [1] 6 Queue classのインスタンス化 HIRO: R Advent Calendar 2014
  • 11. HistoryQueue <- R6Class("HistoryQueue", inherit = Queue, public = list( show = function() { cat("Next item is at index", private$head_idx + 1, "¥n") for (i in seq_along(private$queue)) { cat(i, ": ", private$queue[[i]], "¥n", sep = "") } }, pop = function() { if (private$length() - private$head_idx == 0) return(NULL) private$head_idx <<- private$head_idx + 1 private$queue[[private$head_idx]] } ), private = list( head_idx = 0 ) ) Queue classの継承 show() の追加 method() のオーバーライド HIRO: R Advent Calendar 2014
  • 12. hq <- HistoryQueue$new(5, 6, "foo") hq$show() > Next item is at index 1 > 1: 5 > 2: 6 > 3: foo hq$pop() > [1] 5 hq$show() > Next item is at index 2 > 1: 5 > 2: 6 > 3: foo hq$pop() > [1] 6 Queueのサブクラスである HistoryQueueのインスタンス化 HIRO: R Advent Calendar 2014
  • 13. CountingQueue <- R6Class("CountingQueue", inherit = Queue, public = list( push = function(x) { private$total <<- private$total + 1 super$push(x) }, get_total = function() private$total ), private = list( total = 0 ) ) cq <- CountingQueue$new("x", "y") cq$get_total() > [1] 2 cq$push("z") cq$pop() > [1] "x" cq$pop() > [1] "y" cq$get_total() > [1] 3 Queue classの継承 スーパークラスのメソッドをsuper$で呼び出し HIRO: R Advent Calendar 2014
  • 14. SimpleClass <- R6Class("SimpleClass", public = list(x = NULL) ) NonSharedField <- R6Class("NonSharedField", public = list( e = NULL, initialize = function() e <<- SimpleClass$new() ) ) n1 <- NonSharedField$new() n1$e$x <- 1 n2 <- NonSharedField$new() n2$e$x <- 2 # n2$e$x does not affect n1$e$x n1$e$x > [1] 1 initializeメソッドの中で オブジェクト参照 *initializeメソッドの中ではなく 直接設定される場合、すべてで共有 されてしまう(左の例の場合、 n1$e$x = 2 となる) HIRO: R Advent Calendar 2014
  • 15. NP <- R6Class("NP", portable = FALSE, public = list( x = NA, getx = function() x, setx = function(value) x <<- value ) ) np <- NP$new() np$setx(10) np$getx() > [1] 10 P <- R6Class("P", portable = TRUE, # This is default public = list( x = NA, getx = function() self$x, setx = function(value) self$x <- value ) ) p <- P$new() p$setx(10) p$getx() > [1] 10 non-portable classの場合のみ selfの代わりに <<- 使用可 Portable class: portable=TRUE ・異なるパッケージ間でも継承 ・メンバへのアクセスには、(public) self$x もしくは <<- や private$y が必要 HIRO: R Advent Calendar 2014
  • 16. clsTrnR6 <- R6Class("clsTrnR6", lock=FALSE, public = list( x = NA, initialize = function(x) { self$x <- x }, push_function = function(name, meth) { self[[name]] <- meth environment(self[[name]]) <- environment(self$push_function) } ) ) clsR6 <- clsTrnR6$new(x=4) clsR6$x #[1] 4 clsR6$push_function("predict", function(y) y*self$x) clsR6$predict(11) メソッドの追加 HIRO: R Advent Calendar 2014 lock = FALSE
  • 17. A <- R6Class("A", public = list( initialize = function() { reg.finalizer(self, function(e) print("Finalizer has been called!"), onexit = TRUE) } )) A$new() 1+1 invisible(gc() > "Finalizer has been called!" initializeの中で ファイナライザを呼び出し 最後の処理の結果が.Last.valueに入るので 何か別の処理をする gc()で終了 HIRO: R Advent Calendar 2014
  • 18.  ありがとうございました m(_ _)m  誤訳・誤解等ご指摘ください  あっても大目に見て下さい… HIRO: R Advent Calendar 2014