0

I have two xts-matrices (A and B) were both contain headers in the form of "value1.value2". This label combination is saved for both matrices as characters to avoid R to attach the prefix "X" to the numbers.

A and B are already labeled with their symbol combination.

Now I want to attach matrix B on the right hand-side of A (I used C <- cbind(A,B) or C <- merge.xts(A,B)).

Merging or binding them causes R to attach the X in front of the headers. It can't be undone by
colnames(C) <- as.character(colnames(C))

How can I get rid of it, if I want to use numbers as headers (please note: it's not a file that I am loading, I am trying to bring to outputs together)?

As next step I want to order the columns in an increasing manner and tried:

C <- C[,sort(colnames(C), decreasing = F)]

But R completely messes up the order and seems to randomly arrange the columns. I also tried as.data.frame(cbind(A,B)) and sort the dataframe, but it doesn't improve anything.

I am happy to receive valuable suggestions.

Unfortunately, I can't provide a minimum working example.

Thank you very much!

StableSong
  • 79
  • 11

1 Answers1

0

You can rename the colnames based on the colnames from the individual xts objectsor use a substring like substring(colnames(C), 2).

create data sample:

library(xts)
A <- matrix(1:20, ncol = 2)
colnames(A) <- c("10.20", "20.01")
B <- matrix(20:1, ncol = 2)
colnames(B) <- c("10.10", "10.01")

# as xts objects
A <- as.xts(A, order.by = seq.Date(Sys.Date() - 9, Sys.Date(), by = "day"))
B <- as.xts(B, order.by = seq.Date(Sys.Date() - 9, Sys.Date(), by = "day"))

C <- merge(A, B)

# rename colnames to names before merge to get rid of X in front of name
colnames(C) <- c(colnames(A), colnames(B))

# alternative use substring: 
# colnames(C) <- substring(colnames(C), 2)

C[, sort(colnames(C), decreasing = F)]
           10.01 10.10 10.20 20.01
2020-03-08    10    20     1    11
2020-03-09     9    19     2    12
2020-03-10     8    18     3    13
2020-03-11     7    17     4    14
2020-03-12     6    16     5    15
2020-03-13     5    15     6    16
2020-03-14     4    14     7    17
2020-03-15     3    13     8    18
2020-03-16     2    12     9    19
2020-03-17     1    11    10    20
phiver
  • 23,048
  • 14
  • 44
  • 56