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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With