Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group value in range r

Tags:

r

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!

like image 692
Smasell Avatar asked May 11 '16 11:05

Smasell


People also ask

How do I group data into categories in R?

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.

What does Groupby () do in R?

Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames.

How do you find the range of values in R?

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.

How do I count the number of values in a group in R?

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.


1 Answers

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
like image 51
ztl Avatar answered Sep 28 '22 00:09

ztl