Say I have this database:
Bins=10
df=data.frame(Min=c(0,10,20,30), Max=c(5,16,26,38),val=c(3,11,21,31))
I want to add another column, in which I categorize the values in one column (i.e., column call "val"), by the equal size bins created between the values in two other columns (i.e., the breaks between columns call Min and Max.
I thought I could just use the cut function defining as breaks the sequence between the Min and Max columns, but it does not work.
df$bin=cut(df$val, breaks = seq(from = df$Min, to =df$Max,length.out =Bins) ,include.lowest =TRUE)
Any idea how can I define the breaks used by the function cut on each row?.
>Solution :
You can use mutate() with rowwise() from dplyr package.
df %>%
rowwise() %>%
mutate(bin=cut(val, breaks = seq(from = Min, to =Max,length.out =Bins) ,include.lowest =TRUE))
Output:
Min Max val bin
<dbl> <dbl> <dbl> <fct>
1 0 5 3 (2.78,3.33]
2 10 16 11 (10.7,11.3]
3 20 26 21 (20.7,21.3]
4 30 38 31 (30.9,31.8]