SlideShare ist ein Scribd-Unternehmen logo
1 von 18
第三回R勉強会
R言語のループ処理について
R言語でほかのプログラミング言語と同じ:
●
for文
●
while文
●
repeat文
実行を振り返すためにループがある。。。
for
> for (i in 1:10) cat(pnorm(i)," ")
0.8413447 0.9772499 0.9986501 0.9999683 0.9999997 1 1 1 1 1
for (name in expr_1) expr_2
> for (i in 1:ncol(faithful)){
>
print(c(min(faithful[,i]),max(faithful[,i]),mean(faithful[,i]),median(faithf
ul[,i])))
> }
> xyz = list(42,c(1,2,3),matrix(c(1:4),2,2))
> for (i in 1:length(xyz)) xyz[[i]] = xyz[[i]]+1
[1] 43
[1] 2 3 4
[,1] [,2]
[1,] 2 4
[2,] 3 5
while
> while (i < 5){
print(dnorm(i))
i = i+1
}
[1] 0.3989423
[1] 0.2419707
[1] 0.05399097
[1] 0.004431848
[1] 0.0001338302
while (condition) expr
> x = 2
> repeat{
> print(x)
> x = x^2
> }
...
[1] Inf
[1] Inf
[1] Inf
[1] Inf
[1] Inf
[1] Inf
[1] Inf
[1] Inf
[1]
...
repeat expr
repeat
x = 2
repeat{
print(x)
x = x^2
if(x == Inf ) break
}
[1] 2
[1] 4
[1] 16
[1] 256
[1] 65536
[1] 4294967296
[1] 1.844674e+19
[1] 3.402824e+38
[1] 1.157921e+77
[1] 1.340781e+154
Break 以外には next (AKA ”continue”) もあります
R言語でほかのプログラミング言語と同じ:
●
for文
●
while文
●
repeat文
実行を振り返すためにループがある。。。
Warning: for() loops are used in R code much less often tha
n in
compiled languages. Code that takes a ‘whole object’ view is l
ikely
to be both clearer and faster in R
An introduction to R
(http://cran.r-project.org)
けど。。。
1. Built in functions
maximum = function(mtrx){
mx = mtrx[1,1]
for(i in 1:ncol(abc)){
for(j in 1:length(abc[i,])){
if(mtrx[i,j]>mx) mx = mtrx[i,j]
}
}
return(mx)
}
maximum(abc)
> max(abc)
> system.time(maximum(abc))
ユーザ システム 経過
0.90 0.00 0.91
> system.time(max(abc))
ユーザ システム 経過
0.02 0.00 0.01
> set.seed(42)
> abc =
matrix(matrix(rnorm(10e5),nrow=10e2))
様子はー万だけ
1. Built in functions
数学の手段 R言語の関数
全額 sum
平均 mean
中央値 median
分散 var
共分散 cov
相関 cor
対数 log
値の範囲 range
尺度 scale
R言語の関数はVectorizationということ使って
ベクターのようなオブジェクト一緒に扱って処理します
,2 ,3
1,
2,
3,
,1
58.5
59.558.056.5
157.5156.0 0
57.055.5> apply(myMatrix,1,mean)
[1] 57.0 104.5 58.0
58.0
104.5
57.0
平均
272.5268.0 118.0全額
> apply(myMatrix,2,sum)
[1] 268.0 272.5 118.0
2. apply, lapply, sapply...
Apply – apply function over array margins
> apply(myMatrix,c(1,2),sqrt)
[,1] [,2] [,3]
[1,] 7.449832 7.549834 7.648529
[2,] 12.489996 12.549900 0.000000
[3,] 7.516648 7.615773 7.713624
> sqrt(myMatrix)
2. apply, lapply, sapply...
> set.seed(42)
> abc =
matrix(matrix(rnorm(10e5),nrow=10e2))
my.mean = function(mat){
res.vec = vector()
for (i in 1:ncol(mat)){
my.sum = 0
for (j in 1:length(mat[,i])){
my.sum = my.sum + mat[j,i]
}
my.col.mean = my.sum / length(mat[,i])
res.vec = append(res.vec,my.col.mean)
}
return (res.vec)
}
> apply(abc,1,mean)
> system.time(apply(abc,2,mean))
ユーザ システム 経過
0.01 0.01 0.03
> system.time(my.mean(abc))
ユーザ システム 経過
0.92 0.00 0.92
2. apply, lapply, sapply...
● lapply – apply function over list or vector
● sapply – user-friendly version of lapply
● vapply – similar but return specified values
● rapply – recursive apply
● tapply – apply function to a ragged array
● mapply – apply a function to a multiple list
input
???
output
???
3. plyrのパッケージ
AP PLY + R
パッケージの名前について:
data frame data frame
list array
Input Output 関数名前
ddply
laply
array none a_ply
3. plyrのパッケージ
GET https://api.twitter.com/1.1/statuses/home_timeline.json
[
{
"coordinates": null,
"truncated": false,
"favorited": false,
"created_at": "Mon Jun 27 19:32:19 +0000 2011",
"id_str": "85430275915526144",
"user": {
"profile_sidebar_border_color": "0094C2",
"profile_background_tile": false,
"profile_sidebar_fill_color": "a9d9f1",
"name": "Twitter API",
},
…
...
}
]
3. plyrのパッケージ
in_reply_to_
status_id_s
in_reply_to_
user_id
... user.id user.name ….
$statuses[[99]]$in_reply_to_status_id_str
NULL
$statuses[[99]]$in_reply_to_user_id
NULL
$statuses[[99]]$in_reply_to_user_id_str
NULL
$statuses[[99]]$user
$statuses[[99]]$user$id
[1] 375912401
$statuses[[99]]$user$name
[1] "Super Villain "
nestedParser = function(element,data){
resultMat =
matrix(nrow=length(data),ncol=length(element))
colnames(resultMat) = element
for (i in 1:length(element)){
levels = strsplit(element[i],"$",fixed=TRUE)
for(k in 1:length(data)){
for(j in 1:(length(levels[[1]]))){
if(j == 1){
temp = data[[k]][levels[[1]][j]]
}else{
temp = temp[[1]][levels[[1]][j]]
}
}
resultMat[k,i] = as.character(temp)
}
}
return(resultMat)
}
3. plyrのパッケージ
> nestedParser(c("user$name","text","lang","created_at","id"),tw.data$statuses)
3. plyrのパッケージ
tw.data = laply(tw.data, .fun = function(x){x[c("text","id",...)]})
tw.data = laply(tw.data, function(x) laply(x, identity))
ひとつずつの列を取って:
リストの帰納を避ける:
●
R言語でループ(for, while, repeat)があるけ
どできる限り使わないほうがいいです
●
Vectorizeを使って関数と方法はループより早
くて読みやすいです
● ループはバッグっぽくてデバッグやりにくい
●
R言語のBuild-inの関数やApplyやplyrパッケー
ジなど使いましょう!
4. まとめ

Weitere ähnliche Inhalte

Was ist angesagt?

虚数は作れる!Swift で学ぶ複素数
虚数は作れる!Swift で学ぶ複素数虚数は作れる!Swift で学ぶ複素数
虚数は作れる!Swift で学ぶ複素数
Taketo Sano
 
Rで学ぶデータマイニングI 第8章〜第13章
Rで学ぶデータマイニングI 第8章〜第13章Rで学ぶデータマイニングI 第8章〜第13章
Rで学ぶデータマイニングI 第8章〜第13章
Prunus 1350
 
130604 fpgax kibayos
130604 fpgax kibayos130604 fpgax kibayos
130604 fpgax kibayos
Mikio Yoshida
 
距離まとめられませんでした
距離まとめられませんでした距離まとめられませんでした
距離まとめられませんでした
Haruka Ozaki
 
何もないところから数を作る
何もないところから数を作る何もないところから数を作る
何もないところから数を作る
Taketo Sano
 
インターン講義8日目「データ構造」
インターン講義8日目「データ構造」インターン講義8日目「データ構造」
インターン講義8日目「データ構造」
Hatena::Engineering
 
K010 appstat201201
K010 appstat201201K010 appstat201201
K010 appstat201201
t2tarumi
 

Was ist angesagt? (19)

R's anti sparseness
R's anti sparsenessR's anti sparseness
R's anti sparseness
 
虚数は作れる!Swift で学ぶ複素数
虚数は作れる!Swift で学ぶ複素数虚数は作れる!Swift で学ぶ複素数
虚数は作れる!Swift で学ぶ複素数
 
TopCoder SRM614 解説
TopCoder SRM614 解説TopCoder SRM614 解説
TopCoder SRM614 解説
 
Rで学ぶデータマイニングI 第8章〜第13章
Rで学ぶデータマイニングI 第8章〜第13章Rで学ぶデータマイニングI 第8章〜第13章
Rで学ぶデータマイニングI 第8章〜第13章
 
コードを書けば複素数がわかる
コードを書けば複素数がわかるコードを書けば複素数がわかる
コードを書けば複素数がわかる
 
End challenge Part1
End challenge Part1End challenge Part1
End challenge Part1
 
130604 fpgax kibayos
130604 fpgax kibayos130604 fpgax kibayos
130604 fpgax kibayos
 
距離まとめられませんでした
距離まとめられませんでした距離まとめられませんでした
距離まとめられませんでした
 
すごいHaskell読書会 in 大阪 2週目 #5 第5章:高階関数 (2)
すごいHaskell読書会 in 大阪 2週目 #5 第5章:高階関数 (2)すごいHaskell読書会 in 大阪 2週目 #5 第5章:高階関数 (2)
すごいHaskell読書会 in 大阪 2週目 #5 第5章:高階関数 (2)
 
何もないところから数を作る
何もないところから数を作る何もないところから数を作る
何もないところから数を作る
 
Knn発表資料(R)
Knn発表資料(R)Knn発表資料(R)
Knn発表資料(R)
 
確率プロット
確率プロット確率プロット
確率プロット
 
何もないところから数を作る
何もないところから数を作る何もないところから数を作る
何もないところから数を作る
 
線形計画法入門
線形計画法入門線形計画法入門
線形計画法入門
 
はじめてのパターン認識 第6章 後半
はじめてのパターン認識 第6章 後半はじめてのパターン認識 第6章 後半
はじめてのパターン認識 第6章 後半
 
インターン講義8日目「データ構造」
インターン講義8日目「データ構造」インターン講義8日目「データ構造」
インターン講義8日目「データ構造」
 
K010 appstat201201
K010 appstat201201K010 appstat201201
K010 appstat201201
 
Casual learning machine_learning_with_excel_no7
Casual learning machine_learning_with_excel_no7Casual learning machine_learning_with_excel_no7
Casual learning machine_learning_with_excel_no7
 
ラビットチャレンジレポート 深層学習Day3
ラビットチャレンジレポート 深層学習Day3ラビットチャレンジレポート 深層学習Day3
ラビットチャレンジレポート 深層学習Day3
 

Ähnlich wie 第三回R勉強会

Ähnlich wie 第三回R勉強会 (20)

Rによる繰り返しの並列処理
Rによる繰り返しの並列処理Rによる繰り返しの並列処理
Rによる繰り返しの並列処理
 
PostgreSQL SQLチューニング入門 実践編(pgcon14j)
PostgreSQL SQLチューニング入門 実践編(pgcon14j)PostgreSQL SQLチューニング入門 実践編(pgcon14j)
PostgreSQL SQLチューニング入門 実践編(pgcon14j)
 
PostgreSQLの実行計画を読み解こう(OSC2015 Spring/Tokyo)
PostgreSQLの実行計画を読み解こう(OSC2015 Spring/Tokyo)PostgreSQLの実行計画を読み解こう(OSC2015 Spring/Tokyo)
PostgreSQLの実行計画を読み解こう(OSC2015 Spring/Tokyo)
 
Tokyo r27
Tokyo r27Tokyo r27
Tokyo r27
 
10分で分かるr言語入門ver2.10 14 1101
10分で分かるr言語入門ver2.10 14 110110分で分かるr言語入門ver2.10 14 1101
10分で分かるr言語入門ver2.10 14 1101
 
(Ruby使いのための)Scalaで学ぶ関数型プログラミング
(Ruby使いのための)Scalaで学ぶ関数型プログラミング(Ruby使いのための)Scalaで学ぶ関数型プログラミング
(Ruby使いのための)Scalaで学ぶ関数型プログラミング
 
Programming Haskell Chapter 11 切符番号選び
Programming Haskell Chapter 11 切符番号選びProgramming Haskell Chapter 11 切符番号選び
Programming Haskell Chapter 11 切符番号選び
 
10分で分かるr言語入門ver2.9 14 0920
10分で分かるr言語入門ver2.9 14 0920 10分で分かるr言語入門ver2.9 14 0920
10分で分かるr言語入門ver2.9 14 0920
 
PostgreSQL:行数推定を読み解く
PostgreSQL:行数推定を読み解くPostgreSQL:行数推定を読み解く
PostgreSQL:行数推定を読み解く
 
20190625 OpenACC 講習会 第3部
20190625 OpenACC 講習会 第3部20190625 OpenACC 講習会 第3部
20190625 OpenACC 講習会 第3部
 
C++によるソート入門
C++によるソート入門C++によるソート入門
C++によるソート入門
 
F#入門 ~関数プログラミングとは何か~
F#入門 ~関数プログラミングとは何か~F#入門 ~関数プログラミングとは何か~
F#入門 ~関数プログラミングとは何か~
 
多次元配列の効率的利用法の検討
多次元配列の効率的利用法の検討多次元配列の効率的利用法の検討
多次元配列の効率的利用法の検討
 
JOIss2020 発表資料
JOIss2020 発表資料JOIss2020 発表資料
JOIss2020 発表資料
 
Let's Simulate a Quantum Computer with Pretty Scala
Let's Simulate a Quantum Computer with Pretty ScalaLet's Simulate a Quantum Computer with Pretty Scala
Let's Simulate a Quantum Computer with Pretty Scala
 
[機械学習]文章のクラス分類
[機械学習]文章のクラス分類[機械学習]文章のクラス分類
[機械学習]文章のクラス分類
 
文字列カーネルによる辞書なしツイート分類 〜文字列カーネル入門〜
文字列カーネルによる辞書なしツイート分類 〜文字列カーネル入門〜文字列カーネルによる辞書なしツイート分類 〜文字列カーネル入門〜
文字列カーネルによる辞書なしツイート分類 〜文字列カーネル入門〜
 
Esm lt threading_macro
Esm lt threading_macroEsm lt threading_macro
Esm lt threading_macro
 
Nagoya.R #12 入門者講習
Nagoya.R #12 入門者講習Nagoya.R #12 入門者講習
Nagoya.R #12 入門者講習
 
機械学習
機械学習機械学習
機械学習
 

Mehr von Paweł Rusin (6)

Workflow and development in globally distributed mobile teams
Workflow and development in globally distributed mobile teamsWorkflow and development in globally distributed mobile teams
Workflow and development in globally distributed mobile teams
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
LOD METI
LOD METILOD METI
LOD METI
 
R言語で統計分類基本
R言語で統計分類基本R言語で統計分類基本
R言語で統計分類基本
 
関東第3回ゼロはじめるからR言語勉強会ー グラフ
関東第3回ゼロはじめるからR言語勉強会ー グラフ関東第3回ゼロはじめるからR言語勉強会ー グラフ
関東第3回ゼロはじめるからR言語勉強会ー グラフ
 
課題 (第三回)
課題 (第三回)課題 (第三回)
課題 (第三回)
 

第三回R勉強会

  • 3. for > for (i in 1:10) cat(pnorm(i)," ") 0.8413447 0.9772499 0.9986501 0.9999683 0.9999997 1 1 1 1 1 for (name in expr_1) expr_2 > for (i in 1:ncol(faithful)){ > print(c(min(faithful[,i]),max(faithful[,i]),mean(faithful[,i]),median(faithf ul[,i]))) > } > xyz = list(42,c(1,2,3),matrix(c(1:4),2,2)) > for (i in 1:length(xyz)) xyz[[i]] = xyz[[i]]+1 [1] 43 [1] 2 3 4 [,1] [,2] [1,] 2 4 [2,] 3 5
  • 4. while > while (i < 5){ print(dnorm(i)) i = i+1 } [1] 0.3989423 [1] 0.2419707 [1] 0.05399097 [1] 0.004431848 [1] 0.0001338302 while (condition) expr
  • 5. > x = 2 > repeat{ > print(x) > x = x^2 > } ... [1] Inf [1] Inf [1] Inf [1] Inf [1] Inf [1] Inf [1] Inf [1] Inf [1] ... repeat expr repeat x = 2 repeat{ print(x) x = x^2 if(x == Inf ) break } [1] 2 [1] 4 [1] 16 [1] 256 [1] 65536 [1] 4294967296 [1] 1.844674e+19 [1] 3.402824e+38 [1] 1.157921e+77 [1] 1.340781e+154 Break 以外には next (AKA ”continue”) もあります
  • 7. Warning: for() loops are used in R code much less often tha n in compiled languages. Code that takes a ‘whole object’ view is l ikely to be both clearer and faster in R An introduction to R (http://cran.r-project.org) けど。。。
  • 8. 1. Built in functions maximum = function(mtrx){ mx = mtrx[1,1] for(i in 1:ncol(abc)){ for(j in 1:length(abc[i,])){ if(mtrx[i,j]>mx) mx = mtrx[i,j] } } return(mx) } maximum(abc) > max(abc) > system.time(maximum(abc)) ユーザ システム 経過 0.90 0.00 0.91 > system.time(max(abc)) ユーザ システム 経過 0.02 0.00 0.01 > set.seed(42) > abc = matrix(matrix(rnorm(10e5),nrow=10e2)) 様子はー万だけ
  • 9. 1. Built in functions 数学の手段 R言語の関数 全額 sum 平均 mean 中央値 median 分散 var 共分散 cov 相関 cor 対数 log 値の範囲 range 尺度 scale R言語の関数はVectorizationということ使って ベクターのようなオブジェクト一緒に扱って処理します
  • 10. ,2 ,3 1, 2, 3, ,1 58.5 59.558.056.5 157.5156.0 0 57.055.5> apply(myMatrix,1,mean) [1] 57.0 104.5 58.0 58.0 104.5 57.0 平均 272.5268.0 118.0全額 > apply(myMatrix,2,sum) [1] 268.0 272.5 118.0 2. apply, lapply, sapply... Apply – apply function over array margins > apply(myMatrix,c(1,2),sqrt) [,1] [,2] [,3] [1,] 7.449832 7.549834 7.648529 [2,] 12.489996 12.549900 0.000000 [3,] 7.516648 7.615773 7.713624 > sqrt(myMatrix)
  • 11. 2. apply, lapply, sapply... > set.seed(42) > abc = matrix(matrix(rnorm(10e5),nrow=10e2)) my.mean = function(mat){ res.vec = vector() for (i in 1:ncol(mat)){ my.sum = 0 for (j in 1:length(mat[,i])){ my.sum = my.sum + mat[j,i] } my.col.mean = my.sum / length(mat[,i]) res.vec = append(res.vec,my.col.mean) } return (res.vec) } > apply(abc,1,mean) > system.time(apply(abc,2,mean)) ユーザ システム 経過 0.01 0.01 0.03 > system.time(my.mean(abc)) ユーザ システム 経過 0.92 0.00 0.92
  • 12. 2. apply, lapply, sapply... ● lapply – apply function over list or vector ● sapply – user-friendly version of lapply ● vapply – similar but return specified values ● rapply – recursive apply ● tapply – apply function to a ragged array ● mapply – apply a function to a multiple list input ??? output ???
  • 13. 3. plyrのパッケージ AP PLY + R パッケージの名前について: data frame data frame list array Input Output 関数名前 ddply laply array none a_ply
  • 14. 3. plyrのパッケージ GET https://api.twitter.com/1.1/statuses/home_timeline.json [ { "coordinates": null, "truncated": false, "favorited": false, "created_at": "Mon Jun 27 19:32:19 +0000 2011", "id_str": "85430275915526144", "user": { "profile_sidebar_border_color": "0094C2", "profile_background_tile": false, "profile_sidebar_fill_color": "a9d9f1", "name": "Twitter API", }, … ... } ]
  • 15. 3. plyrのパッケージ in_reply_to_ status_id_s in_reply_to_ user_id ... user.id user.name …. $statuses[[99]]$in_reply_to_status_id_str NULL $statuses[[99]]$in_reply_to_user_id NULL $statuses[[99]]$in_reply_to_user_id_str NULL $statuses[[99]]$user $statuses[[99]]$user$id [1] 375912401 $statuses[[99]]$user$name [1] "Super Villain "
  • 16. nestedParser = function(element,data){ resultMat = matrix(nrow=length(data),ncol=length(element)) colnames(resultMat) = element for (i in 1:length(element)){ levels = strsplit(element[i],"$",fixed=TRUE) for(k in 1:length(data)){ for(j in 1:(length(levels[[1]]))){ if(j == 1){ temp = data[[k]][levels[[1]][j]] }else{ temp = temp[[1]][levels[[1]][j]] } } resultMat[k,i] = as.character(temp) } } return(resultMat) } 3. plyrのパッケージ > nestedParser(c("user$name","text","lang","created_at","id"),tw.data$statuses)
  • 17. 3. plyrのパッケージ tw.data = laply(tw.data, .fun = function(x){x[c("text","id",...)]}) tw.data = laply(tw.data, function(x) laply(x, identity)) ひとつずつの列を取って: リストの帰納を避ける:
  • 18. ● R言語でループ(for, while, repeat)があるけ どできる限り使わないほうがいいです ● Vectorizeを使って関数と方法はループより早 くて読みやすいです ● ループはバッグっぽくてデバッグやりにくい ● R言語のBuild-inの関数やApplyやplyrパッケー ジなど使いましょう! 4. まとめ