R中函数的舍入输出

Jb.*_*Jb. 7 r function

我正试图从一个简单的by()函数中舍入输出R.这就是我所拥有的:

> by(glaciers[,1:3],glaciers$activity.level,mean)

glaciers$activity.level: Active
       aspect  sun.duration      latitude 
-9.444444e+00  1.771778e+03  3.247643e+09 
-------------------------------------------
glaciers$activity.level: Inactive
      aspect sun.duration     latitude 
1.041667e+01 2.067583e+03 4.048301e+09 
-------------------------------------------
glaciers$activity.level: Relict
      aspect sun.duration     latitude 
1.766667e+01 2.168000e+03 2.759283e+09 
Run Code Online (Sandbox Code Playgroud)

如何让我的输出四舍五入到小数点后5位,仍然保留这些因子?

我试过了round(by(glaciers[,1:3],glaciers$activity.level,mean),5)但是得到了一个错误:Non-numeric argument to mathematical function.

hat*_*rix 10

如果您已将输出保存到变量,请说x:

x <- by(glaciers[,1:3],glaciers$activity.level,mean)
Run Code Online (Sandbox Code Playgroud)

然后对每个元素应用round()(在这种情况下,by()的输出是一个列表).

x[] <- lapply(x,round,5)
x
Run Code Online (Sandbox Code Playgroud)

重新分配给x []而不是x允许x保留by()附加到它的属性.

编辑:round()实际上更改了变量的值,但与其打印分离.如果要抑制科学记数法输出格式,请使用format ="f"参数formatC()

> round(1.2345e10,5)
[1] 1.2345e+10
> formatC(1.2345e10,digits=5,format="f")
[1] "12345000000.00000"
Run Code Online (Sandbox Code Playgroud)

所以对最初发布的表达式的修正将是

x[] <- lapply(x,formatC,digits=5,format="f")
Run Code Online (Sandbox Code Playgroud)


Sha*_*ane 6

round()在这种情况下没有意义,因为你正在使用非常大的数字.您想使用format()命令,并选择要显示的位数.例如,要显示3位有效数字:

by(glaciers[,1:3], glaciers$activity.level, function(x) {
      as.numeric(format(mean(x), digits=3))
})
Run Code Online (Sandbox Code Playgroud)


Rob*_*man 4

by(glaciers[,1:3], glaciers$activity.level, function(x){round(mean(x),5)})
Run Code Online (Sandbox Code Playgroud)

更新

这是一个工作示例:

glaciers <- as.data.frame(matrix(rnorm(1000),ncol=4)) 
glaciers[,4] <- sample(0:3,250,replace=TRUE) 
colnames(glaciers) <- c("A","B","C","activity.level") 
by(glaciers[,1:3], glaciers$activity.level, function(x){round(mean(x),5)})
Run Code Online (Sandbox Code Playgroud)