How to cut multiple columns with the same breaks in R?

Viewed 173

I am trying to summarise counts within breaks from multiple columns.
My dataset conains columns of age data and looks like this

1 2
44.550775 43.205206
49.710284 51.914791
... ...

with values between 0 and 70.
I want to count how many values lie within certain ranges (5 year age steps). I know how to get the counts for one column:

> b <- table(cut(df[,1], breaks=seq(0, 70, 5)))
> b
  (0,5]  (5,10] (10,15] (15,20] (20,25] (25,30] (30,35] (35,40] (40,45] 
     13       8      11       6       9      11      18      14       7 
(45,50] (50,55] (55,60] (60,65] (65,70] 
      7       5       0       1       0 

How do I adapt it for multiple columns? What I want is something like this

> [1]
  (0,5]  (5,10] (10,15] (15,20] (20,25] (25,30] (30,35] (35,40] (40,45] 
     13       8      11       6       9      11      18      14       7 
(45,50] (50,55] (55,60] (60,65] (65,70] 
      7       5       0       1       0 
    > [2]
  (0,5]  (5,10] (10,15] (15,20] (20,25] (25,30] (30,35] (35,40] (40,45] 
     10       7      9       3       8      12      14      19       6 
(45,50] (50,55] (55,60] (60,65] (65,70] 
      6       5       3       1       0 

I have tried

data.frame(lapply(bootdata, cut, breaks=seq(0, 70, 5)))

but that just gives me a dataframe of what range the data was in for each individual value instead of counting by column.
Can anyone help? Please ask if I am being unclear.

1 Answers

Example

df=data.frame(matrix(runif(10*3,0,70),10,3))

sapply(df,function(x){table(cut(x,breaks=seq(0,70,5)))})

        X1 X2 X3
(0,5]    2  1  0
(5,10]   1  1  1
(10,15]  0  2  0
(15,20]  1  1  1
(20,25]  0  1  2
(25,30]  0  1  1
(30,35]  2  0  2
(35,40]  1  1  1
(40,45]  2  0  0
(45,50]  0  1  0
(50,55]  0  0  0
(55,60]  0  0  1
(60,65]  0  0  1
(65,70]  1  1  0
Related