Search code examples
rquantmod

Is it a bug that Quantmod overwrites column names when returning Lag output


For example:

> col1<-Lag(c(1,2,3))
> col1
     Lag.1
[1,]    NA
[2,]     1
[3,]     2


> df<-data.frame(a=c(1,2,3))
> df$a<-Lag(df$a)
> df
  Lag.1
1    NA
2     1
3     2

Note that the column headers are Lag.1 rather than the expected a


Solution

  • This isn't specific to quantmod or Lag. It's how replacement works with data.frame columns ($<-.data.frame). If you replace a column with a 1-column matrix that has a column name, the existing column will be removed and replaced with the new column.

    For example:

    df <- data.frame(a=1:3)
    mat <- matrix(3:1, dimnames=list(NULL, "A"))
    df$a <- mat
    

    If you don't want that to happen, you should drop dimensions of the object you're going to use as a replacement.

    df <- data.frame(a=1:3)
    df$a <- drop(Lag(df$a))