Rのtips

abind

デフォルトのRには、rbind, cbindはあるけど、2次元以上の配列をくっつける関数は用意されていない。が、abindライブラリのabindで出来る。

library(abind)
x <- matrix(1:9, nrow=3)
y <- matrix(11:19, nrow=3)
abind(x, y, along=3)
, , 1

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

, , 2

     [,1] [,2] [,3]
[1,]   11   14   17
[2,]   12   15   18
[3,]   13   16   19

三角行列

行列xの上三角部分だけ残して残りの要素を0にするtips

x <- matrix(1:9, nrow=3)
idx <- outer(1:nrow(x), 1:ncol(x), '<=')
ifelse(idx, x, 0)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    0    5    8
[3,]    0    0    9

0詰め

Rには、formatCというprintf風の書式指定付き出力関数がある。

formatC(1, format="d", width=3, flag="0")
[1] "001"