数据框如下所示:
Date | Length .
2005-01-01 - 3400 .
2005-01-02 - 54000 .
2005-01-03 - 266450 .
2005-01-04 - 0 .
2005-01-05 - 0 .
我想细分“ 266450”中的值并将86400分配到下一行,如果该值超过86400,则将剩余的值再次传递到下一行
例如,答案应该是
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
答案 0 :(得分:0)
一个可重现的示例将有助于理解特定问题,但是我认为这里最主要和最有趣的问题是如何在向量上“拆分”和“分散”一个数字。您可以使用整数商和余数/模函数(%%
和%/%
)来执行此操作。例如:
#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
并使用(sapply
和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