2

I have some R code that creates an XTS object, and then performs various cbind operations in the lifetime of that object. Some of my columns have names such as "adx-1". That is fine until another cbind() operation is performed. At that point, any columns with the "-" character are changes to a ".". So "adx-1" becomes "adx.1".

To reproduce:

x = xts(order.by=as.Date(c("2014-01-01","2014-01-02")))
x = cbind(x,c(1,2))
x
           ..2
2014-01-01   1
2014-01-02   2

colnames(x) = c("adx-1")
x
           adx-1
2014-01-01     1
2014-01-02     2

x = cbind(x,c(1,2))
x
           adx.1 ..2
2014-01-01     1   1
2014-01-02     2   2

It doesn't just do this with numbers either. It changes "test-text" to "test.text" as well. Multiple dashes are changed too. "test-text-two" is changed to "test.text.two".

Can someone please explain why this happens and, if possible, how to stop it from happening?

I can of course change my naming schemes, but it would be preferred if I didn't have to.

Thanks!

Patrick
  • 513
  • 4
  • 14

2 Answers2

3

merge.xts converts the column names into syntactic names, which cannot contain -. According to ?Quotes:

 Identifiers consist of a sequence of letters, digits, the period
 ('.') and the underscore.  They must not start with a digit nor
 underscore, nor with a period followed by a digit.

There is currently no way to alter this behavior.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
1

The reason for the behavior is precisely the one Joshua Ulrich highlighted. It's common across many data types in R: you need "valid" names. Here is a great discussion of this "issue".
For data frames, you can pass the option check.names = FALSE as a workaround, but this is not implemented for xts object. This said, there are plenty of other workarounds available to you.
For instance, you could simply rename the columns of interest after very cbind. Using your code, simply add:
colnames(x)[1] <- c("adx-1") to force back your desired column name.
Alternatively, you could consider this gsub solution if you wanted something potentially more systematic.

tchevrier
  • 1,041
  • 7
  • 16