[英]R Optimal way to create time series from start and end dates for groups
我有一個數據集,每個組我有一個開始和結束日期。 我想把這個數據變成一個,每個時間段(月)我對每個組都有一行觀察。
以下是輸入數據的示例,組由id標識:
structure(list(id = c(723654, 885618, 269861, 1383642, 250276,
815511, 1506680, 1567855, 667345, 795731), startdate = c("2008-06-29",
"2008-12-01", "2006-09-27", "2010-02-03", "2006-08-31", "2008-09-10",
"2010-04-11", "2010-05-15", "2008-04-12", "2008-08-28"), enddate = c("2008-08-13",
"2009-02-08", "2007-10-12", "2010-09-09", "2007-06-30", "2010-04-27",
"2010-04-13", "2010-05-16", "2010-04-20", "2010-03-09")), .Names = c("id",
"startdate", "enddate"), class = "data.frame", row.names = c("1",
"2", "3", "4", "6", "7", "8", "9", "10", "11"))
我寫了一個函數並對其進行了矢量化。 該函數采用存儲在每一行中的三個參數,並生成具有組標識符的時間序列。
genDateRange<-function(start, end, id){
dates<-seq(as.Date(start), as.Date(end), by="month")
return( cbind(month=as.character(dates), id=rep(id, length(dates))))
}
genDataRange<-Vectorize(genDateRange)
我運行如下函數來獲取數據幀。 我在輸出中有超過6M的線,所以它需要永遠。 我需要一種更快的方式。
range<-do.call(rbind,genDataRange(dat$startdate, dat$enddate, dat$id))
前十行輸出如下所示:
structure(c("2008-06-29", "2008-07-29", "2008-12-01", "2009-01-01",
"2009-02-01", "2006-09-27", "2006-10-27", "2006-11-27", "2006-12-27",
"2007-01-27", "723654", "723654", "885618", "885618", "885618",
"269861", "269861", "269861", "269861", "269861"), .Dim = c(10L,
2L), .Dimnames = list(NULL, c("month", "id")))
我希望有一個更快的方法來做到這一點。 我認為我過分關注某些事情而忽略了一個更簡單的解決方案。
無需使用生成器函數或rbindlist
因為data.table
可以在沒有它的情況下輕松處理。
# start with a data.table and date columns
library(data.table)
dat <- data.table(dat)
dat[,`:=`(startdate = as.Date(startdate), enddate = as.Date(enddate))]
dat[,num_mons:= length(seq(from=startdate, to=enddate, by='month')),by=1:nrow(dat)]
dat # now your data.table looks like this
# id startdate enddate num_mons
# 1: 723654 2008-06-29 2008-08-13 2
# 2: 885618 2008-12-01 2009-02-08 3
# 3: 269861 2006-09-27 2007-10-12 13
# 4: 1383642 2010-02-03 2010-09-09 8
# 5: 250276 2006-08-31 2007-06-30 10
# 6: 815511 2008-09-10 2010-04-27 20
# 7: 1506680 2010-04-11 2010-04-13 1
# 8: 1567855 2010-05-15 2010-05-16 1
# 9: 667345 2008-04-12 2010-04-20 25
# 10: 795731 2008-08-28 2010-03-09 19
out <- dat[, list(month=seq.Date(startdate, by="month",length.out=num_mons)), by=id]
out
# id month
# 1: 723654 2008-06-29
# 2: 723654 2008-07-29
# 3: 885618 2008-12-01
# 4: 885618 2009-01-01
# 5: 885618 2009-02-01
# ---
# 98: 795731 2009-10-28
# 99: 795731 2009-11-28
# 100: 795731 2009-12-28
# 101: 795731 2010-01-28
# 102: 795731 2010-02-28
這個問題是相關的,但不同之處在於你在問我們是在迭代,而不是復制數據表中的行。
對於大型數據集
library(data.table)
range <- rbindlist(lapply(genDataRange(dat$startdate, dat$enddate, dat$id),as.data.frame))
應該比快
range<-do.call(rbind,genDataRange(dat$startdate, dat$enddate, dat$id))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.