2.11.0から追加されたぽいarrayIndについて
twitterで@kohskeさんから教えて頂いたことを紹介します。
例えば下記のようなdata frameがあったとします。
... | OBS1 | OBS2 | OBS3 | OBS4 |
---|---|---|---|---|
SAMPLE1 | 34 | 12 | 32 | 23 |
SAMPLE2 | 234 | 21 | 23 | 42 |
SAMPLE3 | 20 | 22 | 34 | 1 |
私はこのようなデータに対し要素の大きいものから順に行、列名を列挙したいと思っていました。
これを実現するには要素の大きいものから順にその行列indexを取れれば良さそうです。
しかし、これをorderで下記のようにやると1次元のindexしか得られません。
> obs1 <- c(34,234,20) > obs2 <- c(12,21,22) > obs3 <- c(32,23,34) > obs4 <- c(23,42,1) > df <- data.frame(OBS1=obs1,OBS2=obs2,OBS3=obs3,OBS4=obs4) > row.names(df) <- c("SAMPLE1","SAMPLE2","SAMPLE3") > df OBS1 OBS2 OBS3 OBS4 SAMPLE1 34 12 32 23 SAMPLE2 234 21 23 42 SAMPLE3 20 22 34 1 > order(df, decreasing=T) [1] 2 11 1 9 7 8 10 6 5 3 4 12
これをarrayIndでやると
> ai <- arrayInd(order(df, decreasing=TRUE), dim(df), dimnames(df)) > ai row col SAMPLE2 2 1 SAMPLE2 2 4 SAMPLE1 1 1 SAMPLE3 3 3 SAMPLE1 1 3 SAMPLE2 2 3 SAMPLE1 1 4 SAMPLE3 3 2 SAMPLE2 2 2 SAMPLE3 3 1 SAMPLE1 1 2 SAMPLE3 3 4
のように2次元のindexが得られ、dimnamesオプションをつければ行名も得られます。
列名も加えて書き出したいのでdata frameを作ると
> order.index <- data.frame(SAMPLE=dimnames(ai)[[1]], OBS=names(df)[ai[,2]], ai, row.names=NULL) > order.index SAMPLE OBS row col 1 SAMPLE2 OBS1 2 1 2 SAMPLE2 OBS4 2 4 3 SAMPLE1 OBS1 1 1 4 SAMPLE3 OBS3 3 3 5 SAMPLE1 OBS3 1 3 6 SAMPLE2 OBS3 2 3 7 SAMPLE1 OBS4 1 4 8 SAMPLE3 OBS2 3 2 9 SAMPLE2 OBS2 2 2 10 SAMPLE3 OBS1 3 1 11 SAMPLE1 OBS2 1 2 12 SAMPLE3 OBS4 3 4
という感じになるかと思います。
以上。