Ale
Ale

Reputation: 317

summarise dataset conditioning on variable using dplyr

I want to summarise my dataset grouping the variable age into 5 years age groups, so instead of single age 0 1 2 3 4 5 6... I would have 0 5 10 15 etc. with 80 being my open-ended category. I could do this by categorizing everything by hand creating a new variable, but I am sure there must be a quicker way!

a <- cbind(age=c(rep(seq(0, 90, by=1), 2)), value=rnorm(182))

Any ideas?

Upvotes: 0

Views: 98

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47300

like this ?

library(dplyr)
a %>% data.frame %>% group_by(age_group = (sapply(age,min,80) %/% 5)*5) %>%
 summarize(avg_val = mean(value))

# A tibble: 17 x 2
   age_group      avg_val
       <dbl>        <dbl>
 1         0 -0.151470805
 2         5  0.553619149
 3        10  0.198915973
 4        15 -0.436646287
 5        20 -0.024193193
 6        25  0.102671120
 7        30 -0.350059839
 8        35  0.010762264
 9        40  0.339268917
10        45 -0.056448481
11        50  0.002982158
12        55  0.348232262
13        60 -0.364050091
14        65  0.177551510
15        70 -0.178885909
16        75  0.664215782
17        80 -0.376929230

Upvotes: 1

CPak
CPak

Reputation: 13581

Example data

set.seed(1)
df <- data.frame(age=runif(1000)*100,
                 value=runif(1000))

Simply add the max value of your group to seq(0,80,5) for irregular breaks with c(..., max(age))

library(dplyr)
df %>%
  mutate(age = cut(age, breaks=c(seq(0,80,5), max(age)))) %>%
  group_by(age) %>%
  summarise(value=mean(value))

Output

        age     value
     <fctr>     <dbl>
 1    (0,5] 0.4901119
 2   (5,10] 0.5131055
 3  (10,15] 0.5022297
 4  (15,20] 0.4712481
 5  (20,25] 0.5610872
 6  (25,30] 0.4207203
 7  (30,35] 0.5218318
 8  (35,40] 0.4377102
 9  (40,45] 0.5007616
10  (45,50] 0.4941768
11  (50,55] 0.5350272
12  (55,60] 0.5226967
13  (60,65] 0.5031688
14  (65,70] 0.4652641
15  (70,75] 0.5667020
16  (75,80] 0.4664898
17 (80,100] 0.4604779

Upvotes: 0

Related Questions