migdal menora
migdal menora

Reputation: 167

Counting number of observations with a sequence

I would like to count number of observations with a sequence. In the following example code I would like to have the number of wolfs for sequence of 2 from 0 to 10. How can I do it with the seq command? Here is the example data frame:

 dat <- read.table(text = " category birds    wolfs     snakes
                       yes        3        9         7
                       no         3        8         4
                       no         1        2         8
                       yes        1        2         3
                         ",header = TRUE)

Here is the desired output:

range number of wolfs
0-2       0
2-4       2
4-6       0
6-8       0
8-10      2

Upvotes: 0

Views: 237

Answers (1)

Roland
Roland

Reputation: 132969

Use cut to assign to intervals and then use table to get the counts:

tab <- table(cut(dat$wolfs, (0:5)*2, include.lowest = TRUE, right = FALSE))
setNames(as.data.frame(tab), c("range", "number of wolfs"))
#   range number of wolfs
#1  [0,2)               0
#2  [2,4)               2
#3  [4,6)               0
#4  [6,8)               0
#5 [8,10]               2

Note how you need to decide on which side the intervals are closed.

Upvotes: 2

Related Questions