R logo

R で小数点第○○位まで出したい、というときは、Excel でもおなじみの Round 関数が使える。

round(データ, 桁数)
round(0.12345, 3)
output
0.123

ただこれだと、小数点以下の最後が 0 だった場合、0 より手前までしか表示されない。

round(0.12000, 3)
output
0.12

 

これを、"0.120" のように最後の "0" まで表示させたいときには、format 関数を使うと良い。

format(データ, nsmall = 桁数)
format(0.12000, nsmall = 3)
output
0.120

 

でも、format だけだと、"0" で終わらない数字は四捨五入されない……

テーブルとかで一気に表示したい場合が多いと思うので、どちらも OK にするために、round 関数と format 関数を組み合わせるとbetter。

format(round(データ, 桁数), nsmall = 桁数)

eg.

Amy - c(
format(round(prop.table(table(Data_updated_AD3$Amy, Data_updated_AD3$CS),1),3)[1,2], nsmall = 3),
format(round(prop.table(table(Data_updated_AD3$Amy, Data_updated_AD3$EC),1),3)[1,2], nsmall = 3),
format(round(prop.table(table(Data_updated_AD3$Amy, Data_updated_AD3$DG),1),3)[1,2], nsmall = 3)
)
output
0.120  0.235  0.100 

 

References

にほんブログ村 子育てブログ ワーキングマザー育児へ