Home > Back-end >  Binning and counting into vector
Binning and counting into vector

Time:11-05

so I have to make a function that does binning and counts the different breaks. So what I have for now is:

 binfunc <- function(numbers, breaks) {
  .bincode(numbers, breaks, right = TRUE, include.lowest = FALSE)
} 

The output for an example vector would be:

numbers1 <- c(20, 70, 14, 30)
breaks1 <- c(youth = 18, adult = 40, elder = Inf)
binfunc(numbers1, breaks1)

[1]  1  2 NA  1

But what I want to have as an output is the different breaks counted in a vector like:

c(youth = 1, adult = 2, elder = 1)

Thanks in Advance

CodePudding user response:

Cut already exists, add table

> table(cut(numbers1,c(0,breaks1),labels=names(breaks1),right=T,include.lowest=F))
youth adult elder 
    1     2     1 

CodePudding user response:

Here is another option:

binfunc <- function(numbers, breaks){
  rowSums(sapply(numbers, \(x) (x <breaks[order(breaks)]) )) |>
    (\(d) c(d[1], diff(d)))()
}

numbers1 <- c(20, 70, 14, 30)
breaks1 <- c(youth = 18, adult = 40, elder = Inf)

binfunc(numbers1, breaks1)
#> youth adult elder 
#>     1     2     1

numbers2 <- c(20, 70, 14, 30, 10, 10, 25, 40, 11, 55)
breaks2 <- c(youth = 18, adult = 40, elder = Inf, mid = 25)

binfunc(numbers2, breaks2)
#> youth   mid adult elder 
#>     4     1     2     3
  • Related