R语言中round函数四舍五入保留小数位数

 

001、数值

> a = 3.336345
> round(a)
[1] 3
> round(a, digits = 2)
[1] 3.34
> round(a, digits = 3)
[1] 3.336

 

002、适用于其他数据类型(向量、数据框;不适用于矩阵)

> a <- c(3.345, 5.3243, 8.9779)   ## 适用于向量
> round(a)
[1] 3 5 9
> round(a, digits = 2)
[1] 3.35 5.32 8.98

 

> a <- c(3.3254, 3.87632, 8.3245)   ## 适用于数据框
> b <- c(6.863, 5.324, 9.325)
> c <- c(5.324, 7.373, 5.862)
> d <- data.frame(a, b, c)
> d
        a     b     c
1 3.32540 6.863 5.324
2 3.87632 5.324 7.373
3 8.32450 9.325 5.862
> round(d)
  a b c
1 3 7 5
2 4 5 7
3 8 9 6
> round(d,digits = 2)
     a    b    c
1 3.33 6.86 5.32
2 3.88 5.32 7.37
3 8.32 9.32 5.86

 

> a <- c(3.3254, 3.87632, 8.3245)
> b <- c(6.863, 5.324, 9.325)
> c <- c(5.324, 7.373, 5.862)
> d <- data.frame(a, b, c)
> d <- matrix(d)
> round(d)            ## 不适用于矩阵
Error in round(d) : non-numeric argument to mathematical function
> round(d,digits = 2)
Error in round(d, digits = 2) : 
  non-numeric argument to mathematical function

 

posted @ 2022-04-25 18:04  小鲨鱼2018  阅读(1953)  评论(0编辑  收藏  举报