Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function cut applied to one column using breaks values from other colunms

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading