1

Dataframe looks like this:

Date        |   Length .

2005-01-01  -   3400 . 

2005-01-02  -    54000 .

2005-01-03  -     266450 .

2005-01-04  -     0 . 

2005-01-05  -     0 . 

I want to break down the value in '266450' and distribute 86400 to the next row and if that value exceeds 86400 than pass the remaining to the next row again

For example, the answer should be this

Date        |   Length .

2005-01-01  -   3400 . 

2005-01-02  -    54000 .

2005-01-03  -     86400 .

2005-01-04  -     86400 . 

2005-01-05  -     86400 .

2005-01-06 -      7250  
camille
  • 16,432
  • 18
  • 38
  • 60
  • 2
    Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Oct 11 '18 at 16:32

1 Answers1

1

A reproducible example would be helpful to understand the specific question, but I think the main and most interesting question here is how to "split" and "spread" a number over a vector. You can do this using integer quotient and remainder/modulus functions (%% and %/%). For example:

#function to split a number by some other number
# and spread the integer quotients and remainders
# over vector elements
split_and_spread <- function(x, BY){
 c(rep(BY, x %/% BY), x %% BY)
}

split_and_spread(266450, BY = 86400)
#[1] 86400 86400 86400  7250

and apply over a vector using (sapply and unlist)

x = c(3400, 54000, 266450)

#call with sapply and unlist
unlist(sapply(x, split_and_spread, BY = 86400))
#[1]  3400 54000 86400 86400 86400  7250
Chris Holbrook
  • 2,531
  • 1
  • 17
  • 30
  • your solution works fine but I want the difference to be added to the number at the next index that if there is a number 1000 in the next index. It should be 1000 + 86400 (or whatever is carried from the previous calculation). It will allow to keep the length of the vector same. – Darpit Dave Oct 11 '18 at 19:24
  • I am trying to reproduce the example. I an a little new to it. – Darpit Dave Oct 11 '18 at 19:26