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

how to get a seq of 5 from 0 instead from min to max

I have df that looks like following. I would like to build new variable break following rule:
if max>60, then break includes (0, min, max, and the numbers +/-10 from 0);
if max<=60, then break includes (0, min, max, and the numbers +/-7 from 0).

I might not describe this clearly. but you can see the expected outcome here:

enter image description here

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

what should I do? The tricky part is I need to get the seq from 0 +/-10, not from min to max, every 10.

df<-structure(list(min = c(-9, -18, 3), max = c(49, 62, 18)), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

>Solution :

get_seq <- function(mn,mx,val) {
  vals = unique(c(mn, mx, -1*seq(0,abs(mn),by=val),seq(0,mx,val)))
  vals[order(vals)]
}
df %>% rowwise() %>% 
  mutate(break_seq = case_when(
    max>60~list(get_seq(min,max,10)),
    max<=60~list(get_seq(min,max,7))
  )
)

Output:

    min   max break_seq 
  <dbl> <dbl> <list>    
1    -9    49 <dbl [10]>
2   -18    62 <dbl [10]>
3     3    18 <dbl [5]> 

Or, if you want a character string of those numbers, you could do something like this:

get_seq <- function(mn,mx,val) {
  vals = unique(c(mn, mx, -1*seq(0,abs(mn),by=val),seq(0,mx,val)))
  paste0(vals[order(vals)], collapse=",")
}
df %>% rowwise() %>% 
  mutate(break_seq = case_when(
    max>60~get_seq(min,max,10),
    max<=60~get_seq(min,max,7)
  )
)

Output:

    min   max break_seq                     
  <dbl> <dbl> <chr>                         
1    -9    49 -9,-7,0,7,14,21,28,35,42,49   
2   -18    62 -18,-10,0,10,20,30,40,50,60,62
3     3    18 0,3,7,14,18                   
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