0
    st_day<-c(1,5,10)
endday<-c(4,9,15)
d<-c(1,2,3)
data<-cbind(st_day,endday,d)

days1<-c(1:15)
dose1<-rep(c(1,2,3),each=5)
result <- cbind(days1,dose1)

Hello I have 2 coulmns with starts and end dates and corresponding dose with was a administered for certain duration. How can compute the difference and print out the duration between these two dates. I have given a sample code the expected result.

Thank you.

1 Answers1

1

We can use Map to get the corresponding sequence of the two vectors into a list, then cbind the unlistted 'lst' and the replicated 'd' (based on the lengths of 'lst'

lst <- Map(`:`, st_day, endday)
out <- cbind(unlist(lst), rep(d, lengths(lst)))
akrun
  • 674,427
  • 24
  • 381
  • 486
  • OP's `result` is different, but I guess they made a mistake. – Frank Sep 26 '18 at 17:48
  • @Frank Looks like the OPs result have 5 also have 'd' value as 1 – akrun Sep 26 '18 at 17:49
  • It works for the list but it does not work with dates and time format. I get an error Error in .Primitive(":")(dots[[1L]][[7L]], dots[[2L]][[7L]]) : NA/NaN argument – Ravula Abhigyan Sep 26 '18 at 17:52
  • 1
    @Ravula You can use `seq` instead of `:` ... `data %>% data.frame %>% mutate(days = map2(st_day, endday, ~seq(.x, .y, by="day"))) %>% unnest %>% select(-st_day, -endday)` or similar. You should post an example with that case if you can't figure it out. – Frank Sep 26 '18 at 17:53
  • @RavulaAbhigyan For that you may need `seq` i.e. `lst – akrun Sep 26 '18 at 17:53
  • tried it and got the error " 'from' must be of length 1" – Ravula Abhigyan Sep 26 '18 at 18:27
  • @RavulaAbhigyan If you are using `Map`, it loops through each element of 'from` and `to` for each of the vectors. So, you must be doing something wrong – akrun Sep 26 '18 at 18:28