創建一個函數explode
,該函數將間隔分解爲一行數據幀,每天有一行。使用Map
將explode
應用於每個產生數據幀列表的間隔,每個間隔一個。接下來rbind
將列表中的數據幀合併爲一個大數據幀,即by.date
,每天有一行。最後彙總by.date
成一排,每年/月:
library(zoo) # as.yearmon
explode <- function(start, end, amount) {
dates <- seq(start, end, "day")
data.frame(dates, yearmon = as.yearmon(dates), amount = amount/length(dates))
}
by.date <- do.call("rbind", Map(explode, df$start, df$end, df$amount))
aggregate(amount ~ yearmon, by.date, sum)
的問題使用數據(假設2010年的發生被認爲是2013年),我們得到:
yearmon amount
1 Jan 2013 100.00000
2 Feb 2013 94.91525
3 Mar 2013 105.08475
4 Apr 2013 100.00000
5 May 2013 100.00000
更新:如果內存是一個問題,用它代替explode
。它首先在explode
內彙總,以使其輸出更小。此外,我們已經在DF
消除dates
列,因爲它是隻包括用於調試:
explode <- function(start, end, amount) {
dates <- seq(start, end, "day")
DF <- data.frame(yearmon = as.yearmon(dates), amount = amount/length(dates))
aggregate(amount ~ yearmon, DF, sum)
}
更新2:這是另一種嘗試。它使用rowsum
這是專門用於彙總總和。在我的測試中,這篇文章的數據運行速度提高了10倍。的
explode2 <- function(start, end, amount) {
dates <- seq(start, end, "day")
n <- length(dates)
rowsum(rep(amount, n)/n, format(dates, "%Y-%m"))
}
by.date <- do.call("rbind", Map(explode2, df$start, df$end, df$amount))
rowsum(by.date, rownames(by.date))
可能重複的[值的平分配數跨越的時間段(http://stackoverflow.com/questions/18835463/flat-apportionment-of-values-across-time-periods) – Michele
由於米歇爾。我已經閱讀了平攤分配問題的答案,並不完全確定如何將其應用於我的示例。我需要更多的指導,因爲我對R很陌生,所以還需要一些關於R思維方式中「事情已經完成」的習慣性見解。但是,謝謝你指出! –
在第四行的情況下,你想要的東西分配50美元到四月和50美元可能,或者離開這一個單獨的,因爲它的總持續時間是一個月? –