Say we have the following numerical vector:
y=c(0.111,1.11,11.1,111.1)
I would like it to be rounded as follows:
0.11,1.11,11.1,111
This rule is simple: I want three digits in total! But if the number is large (e.g. 1111 or 11111) then keep all digits, but without any decimals.
Surely, there has to be a simpler solution?:
lapply(y,function(x){
ifelse(nchar(as.integer(x))<1,round(x,digits=3),
ifelse(nchar(as.integer(x))==1,round(x,digits=2),
ifelse(nchar(as.integer(x))==2,round(x,digits=1),
ifelse(nchar(as.integer(x))>2,round(x,digits=0)
))))
}
)
Just use signif
:
y <- c(0.111,1.11,11.1,111.1,1111)
signif(y, pmax(3,trunc(log10(y)+1)))
#[1] 0.111 1.110 11.100 111.000 1111.000
The pmax(...)
part accounts for the case in which the number has 4 or more digits before the decimal (log10
is just a way to count those digits).
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