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  
1
  • 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 and datapasta packages to assist you with that. See also Help me Help you & How to make a great R reproducible example? Commented Oct 11, 2018 at 16:32

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I am trying to reproduce the example. I an a little new to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.