1
votes

I am working with trade dataset with thousands of rows. Every record has a unique key based on a symbol and date. Trade records for a given symbol are irregular, hence using zoo will be natural choice. I need to use lag and merge to create a new dataset. However, I don't know how to setup multi-column index in zoo in order to use lag function. Below is a sample dataset and intended output.

df = data.frame(
    dt = as.Date(c("2015-01-01", "2015-01-05", "2015-01-06",
                   "2015-01-01", "2015-01-02")),
    id = c("i1", "i1", "i1", "i2", "i2"),
    v1 = c(110, 115, 119, 212, 213),
    v2 = c(100, 170, 180, 202, 210),
    v3 = c(11, 13, 16, 22, 24)
)
df$id = as.character(df$id)

And the output should be

2015-01-01, i1, 110, 100, 11, 2015-01-05, i1, 115, 170, 13 
2015-01-05, i1, 115, 170, 13, 2015-01-06, i1, 119, 180, 16 
2015-01-06, i1, 119, 180, 16, NA, NA, NA, NA, NA
2015-01-01, i2, 212, 202, 22, 2015-01-02, i2, 213, 210, 24 
2015-01-02, i2, 213, 210, 24, NA, NA, NA, NA, NA

Point to note that I need to merge complete rows regardless of number of columns. Following is one possible way to solve the "grouped" lag operation based on zoo which will merge complete rows.

doProcessing = function(df){
  icolnames = colnames(df)
  tt = zoo(df, df$dt)
  tt1 = merge(tt, lag(tt, 1))
  colnames(tt1) = c(icolnames, paste0("lag_", icolnames))
  data.frame(tt1, stringsAsFactors=F)
}
fin_df = do.call(rbind, with(df, by(df, list(id), doProcessing, simplify=F)))

This final output frame has every field as factor, which is different than the original data frame.

> str(df)
'data.frame':   5 obs. of  5 variables:
 $ dt: Date, format: "2015-01-05" "2015-01-01" ...
 $ id: chr  "i1" "i1" "i1" "i2" ...
 $ v1: num  115 110 119 212 213
 $ v2: num  170 100 180 202 210
 $ v3: num  13 11 16 22 24

resultant data frame looks like

> str(fin_df)
'data.frame':   5 obs. of  10 variables:
 $ dt    : Factor w/ 4 levels "2015-01-01","2015-01-05",..: 1 2 3 1 4
 $ id    : Factor w/ 2 levels "i1","i2": 1 1 1 2 2
 $ v1    : Factor w/ 5 levels "110","115","119",..: 1 2 3 4 5
 $ v2    : Factor w/ 5 levels "100","170","180",..: 1 2 3 4 5
 $ v3    : Factor w/ 5 levels "11","13","16",..: 1 2 3 4 5
 $ lag_dt: Factor w/ 3 levels "2015-01-05","2015-01-06",..: 1 2 NA 3 NA
 $ lag_id: Factor w/ 2 levels "i1","i2": 1 1 NA 2 NA
 $ lag_v1: Factor w/ 3 levels "115","119","213": 1 2 NA 3 NA
 $ lag_v2: Factor w/ 3 levels "170","180","210": 1 2 NA 3 NA
 $ lag_v3: Factor w/ 3 levels "13","16","24": 1 2 NA 3 NA

What am I doing wrong and How do I get the correct structure as per original data frame?

I asked this question as per this link multipart index in zoo timeseries However I messed up that thread badly, hence didn't receive any response. Need to fix this in a correct way as manual fixing is not elegant and not the "R" way of doing things.

1

1 Answers

1
votes

You have an overlap in indexes for the groups. To avoid a lot of missings, a solution is to use a list containing every id as it's own time-series (zoo objects):

>  myTsList <- tapply(1:nrow(df), df$id, function(x) { zoo::zoo(df[x, ], df$dt[x]) } )
>  myTsList 
$i1
           dt         id v1  v2  v3
2015-01-01 2015-01-01 i1 110 100 11
2015-01-05 2015-01-05 i1 115 170 13
2015-01-06 2015-01-06 i1 119 180 16

$i2
           dt         id v1  v2  v3
2015-01-01 2015-01-01 i2 212 202 22
2015-01-02 2015-01-02 i2 213 210 24

Then you can easily do the grouped lag as you are talking about:

>  res <- lapply(myTsList, function(x) merge(x, lag(x), suffixes=c("","lag")) )
>  res
$i1
           dt.        id. v1. v2. v3. dt.lag     id.lag v1.lag v2.lag v3.lag
2015-01-01 2015-01-01 i1  110 100 11  2015-01-05 i1     115    170    13    
2015-01-05 2015-01-05 i1  115 170 13  2015-01-06 i1     119    180    16    
2015-01-06 2015-01-06 i1  119 180 16  <NA>       <NA>   <NA>   <NA>   <NA>  

$i2
           dt.        id. v1. v2. v3. dt.lag     id.lag v1.lag v2.lag v3.lag
2015-01-01 2015-01-01 i2  212 202 22  2015-01-02 i2     213    210    24    
2015-01-02 2015-01-02 i2  213 210 24  <NA>       <NA>   <NA>   <NA>   <NA> 

of course you can then bind the groups if you want to have a data.frame structure, but we need to convert them first because of the overlap in indexes:

> Reduce(rbind, lapply(res, as.data.frame))
                   dt. id. v1. v2. v3.     dt.lag id.lag v1.lag v2.lag v3.lag
2015-01-01  2015-01-01  i1 110 100  11 2015-01-05     i1    115    170     13
2015-01-05  2015-01-05  i1 115 170  13 2015-01-06     i1    119    180     16
2015-01-06  2015-01-06  i1 119 180  16       <NA>   <NA>   <NA>   <NA>   <NA>
2015-01-011 2015-01-01  i2 212 202  22 2015-01-02     i2    213    210     24
2015-01-02  2015-01-02  i2 213 210  24       <NA>   <NA>   <NA>   <NA>   <NA>

EDIT: If you don't need the time-series at all, but only the final output as a data.frame, then inspired by my suggestion you could do something along:

df$ind <- 1:nrow(df)
myTsList <- tapply(1:nrow(df), df$id, function(x) zoo::zoo(df[x, "ind"], df$dt[x])  )
res <- lapply(myTsList, function(x) merge(x, lag(x)) )
newDf<- Reduce(rbind, lapply(res, as.data.frame))
df$ind <- NULL
as.data.frame(cbind(df[newDf[,1],],df[newDf[,2],]))

          dt id  v1  v2 v3         dt   id  v1  v2 v3
1 2015-01-01 i1 110 100 11 2015-01-05   i1 115 170 13
2 2015-01-05 i1 115 170 13 2015-01-06   i1 119 180 16
3 2015-01-06 i1 119 180 16       <NA> <NA>  NA  NA NA
4 2015-01-01 i2 212 202 22 2015-01-02   i2 213 210 24
5 2015-01-02 i2 213 210 24       <NA> <NA>  NA  NA NA

this will also keep the correct classes etc. from the original data.frame.

EDIT* A simpler dplyr solution:

library(dplyr)
merge( 
    df,
    df %>% group_by(id) %>% mutate(lag=lag(dt)), 
    by.x=c("id","dt"), by.y=c("id","lag"), all.x=TRUE
)

  id         dt v1.x v2.x v3.x         dt v1.y v2.y v3.y
1 i1 2015-01-01  110  100   11 2015-01-05  115  170   13
2 i1 2015-01-05  115  170   13 2015-01-06  119  180   16
3 i1 2015-01-06  119  180   16       <NA>   NA   NA   NA
4 i2 2015-01-01  212  202   22 2015-01-02  213  210   24
5 i2 2015-01-02  213  210   24       <NA>   NA   NA   NA