R - Cut a numeric vector into cells using closed and open intervals

Using the cut() function, I know how to take a numerical vector and place it according to half-open intervals

 (0, 10], (10. 19], (19, 20], (20, 26], etc... 

or

 [0, 10), [10, 19), [19, 20), [20, 26), etc.... 

How can I align a vector with a combination of closed and open intervals like

 (0, 10), [10, 20], (20, 29], (29, 48), [48], (48, 56), etc...? 

Note that I want to create a closed interval consisting of a single number.

Is there a way to use the cut() function or some other function to do this? Is it time for a new feature ?!

EDIT

 boyScale <- function(x) { ret <- ifelse(x < 16.3, 1, ifelse(x = 16.3, 2, ifelse(x < 20.8, 3, ifelse(x = 20.8, 4, ifelse(x < 21.91, 5, ifelse(x = 21.91, 6, ifelse(x < 28.2, 7, ifelse(x = 28.2, 8, ifelse(x < 37.3, 9, ifelse(x = 37.3, 10, 11)))))))))) return(ret) } 

I tried this with the number 25.24 and received the following error message

 Error in ifelse(x = 16.3, 2, ifelse(x < 20.8, 3, ifelse(x = 20.8, 4, ifelse(x < : unused argument (x = 16.3) 

Any ideas?

+4
source share
2 answers

If your input and the desired number. The bins are not too big, you can use nested ifelse s.

 y <- ifelse(x < 10, 1, ifelse(x <= 20, 2, ifelse(x < 30, 3, ifelse(x < 48, 4, ifelse(x <= 48, 5, .....))))) 

Is there any structure in the data that you can use?

0
source

I found using the fancycut package can easily solve this problem.

 fancycut(x,c('(0,10)','[10,20]','(20,29)',...)) 
+1
source

Source: https://habr.com/ru/post/1484568/


All Articles