2013-10-28 106 views
0

我有兩個時間序列,一個是日常時間序列,另一個是離散時間序列。就我而言,我有我需要合併的股票價格和評級,但合併時間序列會根據股票價格保留每日日期,並且該評級適用於日線數據和日期。 一個簡單的合併命令只會查找確切的日期和行情,並將NA應用於不合適的情況。但我想查找完全匹配並填寫最後評分之間的日期。合併不規則時間序列

Daily time series: 

     ticker  date  stock.price 
      AA US Equity 2004-09-06 1 
      AA US Equity 2004-09-07 2 
      AA US Equity 2004-09-08 3 
      AA US Equity 2004-09-09 4 
      AA US Equity 2004-09-10 5 
      AA US Equity 2004-09-11 6 

    Discrete time series 
      ticker  date  Rating Last_Rating 
      AA US Equity 2004-09-08 A   A+ 
      AA US Equity 2004-09-11 AA  A 
      AAL LN Equity 2005-09-08 BB  BB 
      AAL LN Equity 2007-09-09 AA  AA- 
      ABE SM Equity 2006-09-10 AA  AA- 
      ABE SM Equity 2009-09-11 AA  AA- 


    Required Output: 

      ticker  date  stock.price Rating 
      AA US Equity 2004-09-06 1    A+ 
      AA US Equity 2004-09-07 2    A+ 
      AA US Equity 2004-09-08 3    A 
      AA US Equity 2004-09-09 4    A 
      AA US Equity 2004-09-10 5    A 
      AA US Equity 2004-09-11 6    AA 

我會非常感謝您的幫助。

+3

,請讓你的數據容易加載,即'dput'而不是/除了複製粘貼(這是'data.table'簡單滾動合併問題,但你目前的數據顯示太麻煩了) – eddi

回答

1

也許這是你想要的解決方案。 時間序列包zoo中的函數na.locf可用於向前(或向後)傳送值。

library(zoo) 
library(plyr) 
options(stringsAsFactors=FALSE) 

daily_ts=data.frame(
    ticker=c('A','A','A','A','B','B','B','B'), 
    date=c(1,2,3,4,1,2,3,4), 
    stock.price=c(1.1,1.2,1.3,1.4,4.1,4.2,4.3,4.4) 
    ) 
discrete_ts=data.frame(
    ticker=c('A','A','B','B'), 
    date=c(2,4,2,4), 
    Rating=c('A','AA','BB','BB-'), 
    Last_Rating=c('A+','A','BB+','BB') 
    ) 

res=ddply(
    merge(daily_ts,discrete_ts,by=c("ticker","date"),all=TRUE), 
    "ticker", 
    function(x) 
     data.frame(
      x[,c("ticker","date","stock.price")], 
      Rating=na.locf(x$Rating,na.rm=FALSE), 
      Last_Rating=na.locf(x$Last_Rating,na.rm=FALSE,fromLast=TRUE) 
      ) 
    ) 

res=within(
    res, 
    Rating<-ifelse(
     is.na(Rating), 
     Last_Rating,Rating 
     ) 
    )[,setdiff(colnames(res),"Last_Rating")] 

res 

給人

# ticker date stock.price Rating 
#1  A 1   1.1  A+ 
#2  A 2   1.2  A 
#3  A 3   1.3  A 
#4  A 4   1.4  AA 
#5  B 1   4.1 BB+ 
#6  B 2   4.2  BB 
#7  B 3   4.3  BB 
#8  B 4   4.4 BB- 
+0

非常感謝,它工作得很好! – New2R

+0

酷!很高興幫助。 – cryo111

相關問題