I want to have make intervals and to count the number of observations pro interval.
Then, I want to count the number of observations with a condition (here, the number of cars which have 3 or 4 gears) pro interval.
For now, I did something like this:
data(mtcars)
tb1 = table(
cut(mtcars$mpg,
breaks = seq.int(from = min(mtcars$mpg), to = max(mtcars$mpg) 1, by = 5))) %>%
as.data.frame()
But I have trouble constructing my intervals and I do not know how to say that I want to count the number of observations with a condition.
I would finally like something like this:
intervals obs gear_3 gear_4
[10,15) 5 5 0
[15, 20) 13 8 2
[20, 25) 8 2 6
[25, 30) 2 0 1
[30, 35) 4 0 3
CodePudding user response:
Something like this?
library(dplyr)
mtcars %>%
mutate(bin = as.numeric(cut(mpg, seq(min(mpg), max(mpg), 5)))) %>%
count(cyl, bin)
#> cyl bin n
#> 1 4 3 5
#> 2 4 4 4
#> 3 4 NA 2
#> 4 6 2 4
#> 5 6 3 3
#> 6 8 1 6
#> 7 8 2 6
#> 8 8 NA 2