1

If I use cbind to merge two matrices or data.frames that have the same colnames those colnames stay the same in the new matrix or data.frame:

df <- data.frame(test = c(1,2))
df.merge <- cbind(df,df)

df.merge
test test
1    1    1
2    2    2

However, if I do the same with an xts object, a numerical value is added to the colnames:

df.xts <- xts(df, order.by = as.POSIXct(c("2019-02-18 13:00","2019-02-18 14:00"), tz = "UTC"))
df.xts.merge <- cbind(df.xts, df.xts)

df.xts.merge
                    test test.1
2019-02-18 13:00:00    1      1
2019-02-18 14:00:00    2      2

Is there a way to prevent renaming of the columns by merging xts objects?

phiver
  • 23,048
  • 14
  • 44
  • 56
smoff
  • 592
  • 5
  • 21
  • Is there any useful reason why you would want this behaviour? – phiver Feb 18 '19 at 13:15
  • I have time series files with different amounts of columns. Those columns are named according to some parameters. In most of the files the parameters are the same. It simply would be easier if the new columns would have the same names. – smoff Feb 18 '19 at 13:18
  • Hmmm, maybe do something like `df.xts.merge <- cbind(as.data.frame(df.xts), as.data.frame(df.xts))` as a result you will get a df instead of xts object however you can easly convert it into xts the solution is [here](https://stackoverflow.com/questions/4297231/converting-a-data-frame-to-xts) – Adamm Feb 18 '19 at 13:24
  • But you can't extract the second column based on the name if they are equal. If you do something like this: `df.merge[, which(names(df.merge)=="test")]` the return will also be test and test.1. Just using the column name (`df$test` or `df[ , "test"]` will not give both columns, but only the first column. But `cbind.xts` uses `merge.xts` and `merge.xts` fixes duplicate column names. You could always do a `names(df.xts.merge) <- c("test", "test")` or as @Adamm says first a `as.data.frame` call, but that might affect the joining on dates that `merge.xts` performs. – phiver Feb 18 '19 at 13:28
  • Since I need the joining on dates which `merge.xts` does, I now save all the parameters to a vector and name my `xts` object after the merge. Basically it's now what @phiver suggests: `names(df.xts.merge) <- c("test", "test")` Thank you guys. – smoff Feb 18 '19 at 13:41

0 Answers0