Column Name Matching in xts Objects
On Thu, Nov 14, 2013 at 12:06 PM, Pooya Lalehzari
<plalehzari at platinumlp.com> wrote:
Hello,
I noticed an unexpected behavior when using the xts object and I was wondering if anyone knows why that happens. I have a code to create a new column and copy one of the columns to the new column (please see below):
library(xts)
df = data.frame(stringsAsFactors=FALSE)
df[1:3,"date"] = c("2001-1-1","2001-1-2","2001-1-3")
df[1:3,"col1"] = c(1:3)
df[1:3,"col2"] = c(-1:-3)
df[1:3,"col3"] = c(101:103)
rownames(df)= df$date
df2 = as.xts(df)
View(df2)
Col_To_Copy = "col1"
df2$NewCol = df2[,colnames(df2)==Col_To_Copy]
View(df2)
This code works, expect, I noticed that when the Col_To_Copy is not found, the last column is renamed to "NewCol". For example:
library(xts)
df = data.frame(stringsAsFactors=FALSE)
df[1:3,"date"] = c("2001-1-1","2001-1-2","2001-1-3")
df[1:3,"col1"] = c(1:3)
df[1:3,"col2"] = c(-1:-3)
df[1:3,"col3"] = c(101:103)
rownames(df)= df$date
df2 = as.xts(df)
View(df2)
Col_To_Copy = "col5" # the only line changed
df2$NewCol = df2[,colnames(df2)==Col_To_Copy]
View(df2)
In this case, the last column's name is changed to "NewCol". Is that behavior expected for xts objects?
xts doesn't have a $<- method, so $<-.zoo is dispatched. I'm not familiar with the function, but the behavior you found is explicitly defined, so that seems to suggest it was intended.
From "$<-.zoo":
wi <- match(x, colnames(object))
if(is.na(wi)) {
object <- cbind(object, value)
if(is.null(dim(object))) dim(object) <- c(length(object), 1)
colnames(object)[NCOL(object)] <- x
} else {
...
Best,
--
Joshua Ulrich | about.me/joshuaulrich
FOSS Trading | www.fosstrading.com