TTS
TTS

Reputation: 1928

Find closest multiple above and below value R

I am trying to determine the values above and below a variable that fall on a multiple, preferably in a dplyr::mutate.

In this simplified example. I want to determine the multiple of 50 both above and below my values of x. I am under the impression cut is what I should use, but I haven't gotten it to work.

df <- data.frame(
  x = c(265, 617, 88, 99, 143, 378)
)

    x
1 265
2 617
3  88
4  99
5 143
6 378
desired_result <- data.frame(
  x = c(265, 617, 88, 99, 143, 378),
  above = c(300, 650, 100, 100, 150, 400),
  below = c(250, 600, 50, 50, 100, 350)
) 

    x above below
1 265   300   250
2 617   650   600
3  88   100    50
4  99   100    50
5 143   150   100
6 378   400   350

Upvotes: 0

Views: 161

Answers (2)

Timon
Timon

Reputation: 123

You could use the modulus operator %%:

df %>% 
 mutate(above = x - (x %% 50) + 50, 
        below = x - (x %% 50))

Output:

    x above below
1 265   300   250
2 617   650   600
3  88   100    50
4  99   100    50
5 143   150   100
6 378   400   350

Upvotes: 1

Jon Spring
Jon Spring

Reputation: 66445

df$above = ceiling(df$x/50)*50
df$below = floor(df$x/50)*50


    x above below
1 265   300   250
2 617   650   600
3  88   100    50
4  99   100    50
5 143   150   100
6 378   400   350

Upvotes: 2

Related Questions