setoya-blog

システム開発技術、データ分析関連でお勉強したことや、山奥生活を綴る、テンション低めなブログです。

Rで少数点X桁以下で切り捨て

Rの普通のroundだと切り捨てではなく、四捨五入っぽく(完全な四捨五入ではない)なるので、簡単な関数を作る。floor関数は整数以下を切り捨てるので、以下のようにすればよい。

cut_digits <- function(x, digits=0) {
  return (floor(x * 10^digits) /10^digits)
}
> x <- rnorm(10, 100, 5)
> x
 [1]  96.44840 101.14957  98.63229 106.86199  96.84119 103.29264  97.18442
 [8] 102.71183 100.10490 105.09200
> cut_digits(x, digits=2)
 [1]  96.44 101.14  98.63 106.86  96.84 103.29  97.18 102.71 100.10 105.09