user12388610
user12388610

Reputation: 207

In R, how can I group by according to range?

I have one raw dataset like a below table.

  likes age
1  2295  61
2   740  69
3   210  57
4   207  49
5  1226  51
6  9016  63

Using this dataset, my desired output is also like a below table

new_age        likes
age <60      1643
age >60      12051

new_age is divided into two ranges. One is below 60, other is above 60.

Could you please help make this desired output?

Dput data is below:

structure(list(likes = c(2295L, 740L, 210L, 207L, 1226L, 9016L), age = c(61, 69, 57, 49, 51, 63)), class = "data.frame", row.names = c(NA, -6L))

Upvotes: 1

Views: 51

Answers (1)

akrun
akrun

Reputation: 887601

We can create the group with a logical expression

library(dplyr)
df1 %>%
    group_by(new_age = c('age > 60', 'age < 60')[(age < 60) + 1]) %>%
    summarise(likes = sum(likes))
# A tibble: 2 x 2
#  new_age  likes
#  <chr>    <int>
#1 age < 60  1643
#2 age > 60 12051

Upvotes: 4

Related Questions