Smasell
Smasell

Reputation: 1228

Group value in range 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!

Upvotes: 10

Views: 19297

Answers (3)

lmo
lmo

Reputation: 38510

Here is a full solution, including your sample data:

df <- data.frame(name=c("r", "h", "s", "l", "e", "m"), value=c(35,20,16,40,23,40))
# get categories
df$groups <- cut(df$value, breaks=c(0,21,30,Inf))

# calculate group counts:
table(cut(df$value, breaks=c(0,21,30,Inf)))

If Inf is a little too extreme, you can use max(df$value) instead.

Upvotes: 7

akrun
akrun

Reputation: 887571

We can use

library(data.table)
setDT(input)[,.(num=.N) ,
  .(range=cut(value, breaks = c(0,20, 30, Inf), labels = c("0-20", "21-30", "30-")))]

Upvotes: 2

ztl
ztl

Reputation: 2602

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

Upvotes: 10

Related Questions