rarfel
rarfel

Reputation: 13

How to round to the next hundred in R

I would like to round my numbers in my df by 100, but 25, 50 or 75 should be 100, 125 should be 100, 150 or 175 should be 200. 220 should be 200 and so on.

In other words, if number is less then 100, then it should be rounded to 100, larger numbers than 100 should be rounded down if they are less than 50 otherwise up to nearest houndred number.

Lets say that my dataframe is

    df <- data.frame(replicate(1,sample(0:999,100,rep=TRUE)))
colnames(df) <- c("data")

I tried this:

result <- df %>% 
  mutate(
    data = round(if_else(data <= 100, 100, as.numeric(data)), 100)
  )

But only first part works, if number is less than 100, make it 100. What Im doing wrong?

Upvotes: 0

Views: 916

Answers (3)

Uwe
Uwe

Reputation: 42544

The round() function has the digits parameter which indicates the number of decimal places to use. In order to round to the next hundred use digits = -2L. This will avoid to divide by hundred, round, multiply by hundred.

Special treatment is required for values below 100. So, using G. Grothendieck's pmax() approach for its conciseness

x <- seq(25, 225, 25)
x
[1]  25  50  75 100 125 150 175 200 225
pmax(100, round(x, -2L))
[1] 100 100 100 100 100 200 200 200 200

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269586

Check if it is less than 100 and then use 100 or else round:

x <- c(25, 50, 75, 125, 150, 175, 220)
ifelse(x < 100, 100, 100 * round(x / 100))
## [1] 100 100 100 100 200 200 200

This variation also works:

pmax(100, 100 * round(x / 100))
## [1] 100 100 100 100 200 200 200

Upvotes: 6

Cettt
Cettt

Reputation: 11981

here is an easy way to do this: first divide by 100 then round and then multiply by 100:

set.seed(1)
data.frame(data = sample(0:999, 10)) %>% 
  mutate(rounded_data = round(data /100) * 100)

       data rounded_data
1   265          300
2   371          400
3   571          600
4   905          900
5   200          200
6   893          900
7   939          900
8   656          700
9   624          600
10   61          100

If you want to round only when the number is larger than 100 you can use if_else:

 set.seed(1)
    data.frame(data = sample(0:999, 10)) %>% 
      mutate(rounded_data = if_else(data < 100, 100, round(data /100) * 100))

Upvotes: 2

Related Questions