Rilcon42 Rilcon42 - 5 months ago 13
R Question

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

For example:

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

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

Note that the column headers are
rather than the expected


This isn't specific to quantmod or Lag. It's how replacement works with data.frame columns ($< 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))