在R中按函数舍入输出 [英] Rounding output from by function in R
问题描述
我试图在 R
中通过()函数从简单的中取整输出。这是我的:
> (冰川[,1:3],冰川$ activity.level,mean)
冰川$ activity.level:活动
aspect sun.duration latitude
-9.444444e + 00 1.771778e + 03 3.247643e + 09
------------------------------------- ------
冰川$ activity.level:停用
方面sun.duration纬度
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
我怎么能得到我的输出轮到5位小数,并仍然保持这些因素?
我试过了: (冰川[,1:3],冰川$ activity.level,mean),5)
,但会得到一个错误:数学函数的非数字参数 code>。
如果您已经将输出保存到变量中,比如说x:
x < - by(glaciers [, 1:3],冰河$ activity.level,mean)
然后将round (在这种情况下,by()的输出是一个列表)。
x [] < - lapply(x,round ,5)
x
重新赋值给x []而不是x允许x保留附加属性从()开始。
编辑:round()实际上改变了变量的值,但与其打印分离。如果您想要抑制科学记数法输出格式,请对formatC()使用format =f参数
$ p $ > round(1.2345e10,5)
[1] 1.2345e + 10
> formatC(1.2345e10,digits = 5,format =f)
[1]12345000000.00000
$ b $因此,对原先公布的表达式的修正将是:
x [] < - lapply(x,formatC, digits = 5,format =f)
I'm trying to round an output from a simple by()
function in R
. This is what I have:
> 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
How can I get my output to round to say 5 decimal places, and still keep the factors?
I've tried: round(by(glaciers[,1:3],glaciers$activity.level,mean),5)
but get an error: Non-numeric argument to mathematical function
.
If you already have the output saved to a variable, say x:
x <- by(glaciers[,1:3],glaciers$activity.level,mean)
Then apply round() to each element (the output of by() in this case is a list).
x[] <- lapply(x,round,5)
x
reassigning to x[] rather than x allows x to retain attributes attached to it from by().
Edit: round() actually changes the value of the variables but is decoupled from its printing. If you want to suppress the scientific notation output format, use format="f" argument to formatC()
> round(1.2345e10,5)
[1] 1.2345e+10
> formatC(1.2345e10,digits=5,format="f")
[1] "12345000000.00000"
So the correction to the expression originally posted would be
x[] <- lapply(x,formatC,digits=5,format="f")
这篇关于在R中按函数舍入输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!