2015-12-15 51 views
2

我想從原始數據如何使用特定函數來檢索正確的日期,使用重複信息填充新的df?

startdate = c("2015-12-20", "2014-01-21", "2013-04-09") 
endates = c("2015-12-25", "2014-01-31", "2013-04-13") 
data = c(20, 30, 40) 
df <- data.frame(startdate, endates, data) 

我想這個數據幀看起來像這樣加的天新行,但重複的信息。

 dates   sd   ed newdata 
1 2015-12-20 2015-12-20 2015-12-25  20 
2 2015-12-21 2015-12-20 2015-12-25  20 
3 2015-12-22 2015-12-20 2015-12-25  20 
4 2015-12-23 2015-12-20 2015-12-25  20 
5 2015-12-24 2015-12-20 2015-12-25  20 
6 2015-12-25 2015-12-20 2015-12-25  20 
7 2014-01-21 2014-01-21 2014-01-31  30 
8 2014-01-22 2014-01-21 2014-01-31  30 
9 2014-01-23 2014-01-21 2014-01-31  30 
10 2014-01-24 2014-01-21 2014-01-31  30 
11 2014-01-25 2014-01-21 2014-01-31  30 
12 2014-01-26 2014-01-26 2014-01-31  30 
13 2014-01-27 2014-01-26 2014-01-31  30 
14 2014-01-28 2014-01-26 2014-01-31  30 
15 2014-01-29 2014-01-26 2014-01-31  30 
16 2014-01-30 2014-01-26 2014-01-31  30 
17 2014-01-31 2014-01-26 2014-01-31  30 
18 2013-04-09 2013-04-18 2013-04-13  40 
19 2013-04-10 2013-04-18 2013-04-13  40 
20 2013-04-11 2013-04-18 2013-04-13  40 
21 2013-04-12 2013-04-18 2013-04-13  40 
22 2013-04-13 2013-04-18 2013-04-13  40 

我已經通過構建通過這個功能擴展在兩個日期之間的正確日期

timerange <- function(startvec, endvec) { 
dates <- seq(as.Date(startvec), as.Date(endvec), by="days") 
return(dates) 
} 

現在是一個函數,我怎麼可能去把我的DF通過此功能,獲取正確的開始日期,並用重複的信息填充新的數據框?

+0

我認爲在18:22的預期輸出「sd」應該是「2013-04-09」 – akrun

回答

1

我們首先需要將factor類'Date'列轉換爲Date類。然後,使用data.table,我們將'data.frame'轉換爲data.tablesetDT(df)),按行的順序分組(1:nrow(df)),我們得到'startdate'的seq爲'endates',並與其他列一起獲取預期的產出。

df[1:2] <- lapply(df[1:2], as.Date) 
library(data.table) 
res <- setDT(df)[, list(dates=seq(startdate, endates, by = '1 day'), 
     sd= startdate, ed=endates, newdata= data), 
        by = 1:nrow(df)][, nrow:= NULL][] 

res 
#   dates   sd   ed newdata 
# 1: 2015-12-20 2015-12-20 2015-12-25  20 
# 2: 2015-12-21 2015-12-20 2015-12-25  20 
# 3: 2015-12-22 2015-12-20 2015-12-25  20 
# 4: 2015-12-23 2015-12-20 2015-12-25  20 
# 5: 2015-12-24 2015-12-20 2015-12-25  20 
# 6: 2015-12-25 2015-12-20 2015-12-25  20 
# 7: 2014-01-21 2014-01-21 2014-01-31  30 
# 8: 2014-01-22 2014-01-21 2014-01-31  30 
# 9: 2014-01-23 2014-01-21 2014-01-31  30 
#10: 2014-01-24 2014-01-21 2014-01-31  30 
#11: 2014-01-25 2014-01-21 2014-01-31  30 
#12: 2014-01-26 2014-01-21 2014-01-31  30 
#13: 2014-01-27 2014-01-21 2014-01-31  30 
#14: 2014-01-28 2014-01-21 2014-01-31  30 
#15: 2014-01-29 2014-01-21 2014-01-31  30 
#16: 2014-01-30 2014-01-21 2014-01-31  30 
#17: 2014-01-31 2014-01-21 2014-01-31  30 
#18: 2013-04-09 2013-04-09 2013-04-13  40 
#19: 2013-04-10 2013-04-09 2013-04-13  40 
#20: 2013-04-11 2013-04-09 2013-04-13  40 
#21: 2013-04-12 2013-04-09 2013-04-13  40 
#22: 2013-04-13 2013-04-09 2013-04-13  40 
相關問題