Home > database >  Leaner Code to reduce multiple replace() functions
Leaner Code to reduce multiple replace() functions

Time:09-23

To optimize my code I am looking for a way to combine many successive replace() functions. I have a list of numbers between 1 and 2500. Each number should be rounded up to the next higher hundred (5 -> 100, 136 -> 200, etc.) category. Is there a more elegant solution for this?

At the moment it looks like this:

ls <- c(1,126,1399,857,94,543)

ls <- replace(ls, ls > 1 & ls < 100, 100)
ls <- replace(ls, ls > 100.1 & ls < 200, 200)
ls <- replace(ls, ls > 200.1 & ls < 300, 300)

and so on...

CodePudding user response:

Use ceiling to round up to the nearest higher integer:

ceiling(ls / 100) * 100
#[1]  100  200 1400  900  100  600
  • Related