I have my table(input)
name value
Rob 35
Helen 20
Sergey 16
Linn 40
Elena 23
Mary 40
And I want to count how many of my users is in custom range (0-20,21-30,>30)(output):
range num
0-20 2
21-30 1
30- 3
THX! Sorry if this theme not new, but I can't find answer!
The group_by() method in tidyverse can be used to accomplish this. When working with categorical variables, you may use the group_by() method to divide the data into subgroups based on the variable's distinct categories.
Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames.
We can find the range by performing the difference between the minimum value in the vector and the maximum value in the given vector. We can find maximum value using max() function and minimum value by using min() function.
Group By Count in R using dplyr You can use group_by() function along with the summarise() from dplyr package to find the group by count in R DataFrame, group_by() returns the grouped_df ( A grouped Data Frame) and use summarise() on grouped df to get the group by count.
Using dplyr
, you can create (mutate
) a new column indicating in which interval the value belongs (using cut
) and then use this column to group your values and count (n()
) how many of them you have:
library(dplyr)
df %>% mutate(cuts = cut(value, c(0, 20, 30, Inf))) %>%
group_by(cuts) %>%
summarize(n=n())
# cuts n
# (fctr) (int)
# 1 (0,20] 2
# 2 (20,30] 1
# 3 (30,Inf] 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With