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

Time:07-01

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?.

CodePudding user response:

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]

If, instead of the bin column showing a factor variable's range , you could do this to have bin be the midpoint of that range:

f <- function(s,e,b,val) {
  x = seq(s,e,length.out = b)
  max(x[x<val])   (min(x[x>val])-max(x[x<val]))/2
}

df %>% 
  rowwise() %>% 
  mutate(bin=f(Min, Max, Bins, val))

Output:

    Min   Max   val   bin
  <dbl> <dbl> <dbl> <dbl>
1     0     5     3  3.06
2    10    16    11 11   
3    20    26    21 21   
4    30    38    31 31.3 
  • Related