Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round sequence of numbers to chosen numbers

Tags:

r

I got a vector of numbers from 0 to 1. I'd like to divide them to X amount of groups - for example if X=5, then round the numbers to 5 groups: all numbers from 0 to 0.2 will be 0, all from 0.2 to 0.4 will be 0.2, etc.

For example, if I have x <- c(0.34,0.07,0.56) and X=5 like the above explanation, I'll get (0.2, 0, 0.4).

So far, the only way I found to that is by looping over the entire vector. Is there a more elegant way to do that?

like image 970
shakedzy Avatar asked Mar 11 '23 17:03

shakedzy


1 Answers

You can simply do:

floor(x*X)/X
# [1] 0.2 0.0 0.4

More testing cases:

X = 10
floor(x*X)/X
# [1] 0.3 0.0 0.5
X = 2
floor(x*X)/X
# [1] 0.0 0.0 0.5
X = 5
floor(x*X)/X
# [1] 0.2 0.0 0.4

Data:

x <- c(0.34,0.07,0.56)
like image 173
Psidom Avatar answered Mar 24 '23 13:03

Psidom