简体   繁体   中英

divide numeric vector into intervals every n-th

I have this data and would like to categorize each number every n-th number (example 2). Using cut or cut_interval, is not "cutting" it. Any suggestions very much welcome. Thanks!

haves <- data.frame(  
    some_vector = c(1,2,2,3,4,5,6,7,8)    
)
haves$category <- cut_interval(df$some_vector, n=2)
haves

wants <- data.frame(    
    some_vector = c(1,2,2,3,4,5,6,7,8)
    ,category = c(1,1,1,2,2,3,3,4,4)   
)
wants

This should do (for positive numbers)

cut_interval <- function(x, n) ceiling(x / n)

cut_interval(haves$some_vector, n=2)
# [1] 1 1 1 2 2 3 3 4 4

Anyway cut() should be able to cut it (with improvements from @Henrik so it generalises):

cut(haves$some_vector, c(-Inf, seq(2, max(haves$some_vector), by = 2), Inf), labels = FALSE)
# [1] 1 1 1 2 2 3 3 4 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM