Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: decimal ceiling

I need a decimal variant of ceiling and floor functions. Something like signif with an option to choose in which direction to round.

For example, I need the number 2.63 to be transformed into 2.7, and not 3 (ceiling) or 2.6 (signif(2.63,2)).


The only solutions I can think of is to multiply by 10, then take ceiling and divide back by 10. ceiling(2.63*10)/10
I'm sure, there must be a more elegant solution.


My questions is quite similar to this one.

like image 646
ikashnitsky Avatar asked Mar 04 '16 22:03

ikashnitsky


Video Answer


3 Answers

@42- answer in comment seems too useful to be just left in comment, hence this wiki-post.

You can create your own functions and adapt floor and ceiling fonctions, adding a level option to mimic the digits parameter of round function like this:

floor_dec <- function(x, level=1) round(x - 5*10^(-level-1), level)
ceiling_dec <- function(x, level=1) round(x + 5*10^(-level-1), level)

Examples:

# floor
floor_dec(1.259, 2)
[1] 1.25
floor_dec(1.9, 0)
[1] 1
floor_dec(29, -1)
[1] 20
floor_dec(1.251, 2)
[1] 1.25
floor_dec(1.2, 0)
[1] 1
floor_dec(23, -1)
[1] 20

# ceiling
ceiling_dec(1.259, 2)
[1] 1.26
ceiling_dec(1.9, 0)
[1] 2
ceiling_dec(29, -1)
[1] 30
ceiling_dec(1.251, 2)
[1] 1.26
ceiling_dec(1.2, 0)
[1] 2
ceiling_dec(23, -1)
[1] 30
like image 121
2 revs Avatar answered Nov 04 '22 10:11

2 revs


I want to define a very similar function to @42. Instead of having the floor function defined by how many decimal places you want, I want to define the number of sig figs:

floor_dec <- function(x, sigDig=1) {
  mostSig = ceiling(log10(abs(x)))
  floor(x*10^(sigDig-mostSig))*10^-(sigDig-mostSig)
}

> floor_dec(21.259, 4)
[1] 21.25
> floor_dec(21.259, 3)
[1] 21.2
> floor_dec(21.259, 2)
[1] 21
> floor_dec(21.259, 1)
[1] 20
> floor_dec(.259, 4)
[1] 0.259
> floor_dec(.259, 3)
[1] 0.259
> floor_dec(.259, 2)
[1] 0.25
> floor_dec(.259, 1)
[1] 0.2
> floor_dec(1.2, 0)
[1] 0
> floor_dec(23, -1)
[1] 0

Note that sigDif requires positive integers as input. Just like the prompter guesses, I find the position of the most significant digit, move the decimal place for the appropriate floor and then move the decimal place so that the input's most significant digit is the same as the output.

like image 39
Jeff Avatar answered Nov 04 '22 09:11

Jeff


This answer does not have the problem commented in previous answer, though sadly is based on the unwanted answer in the OP:

customCeiling <- function(x, Decimals=1) {
  x2<-x*10^Decimals
  ceiling(x2)/10^Decimals
}

customFloor <- function(x, Decimals=1) {
  x2<-x*10^Decimals
  floor(x2)/10^Decimals
}
like image 22
Ferroao Avatar answered Nov 04 '22 10:11

Ferroao