Search code examples
rtime-seriesxts

Adding column names in XTS and changing dates in XTS


The xts looks like:

An ‘xts’ object on 1970-01-02 05:30:00/1976-03-29 05:30:00 containing:
  Data: num [1:2279, 1] 0.295 0.316 0.315 0.301 0.292 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : NULL
  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
  Original class: 'double'  
  xts Attributes: NULL

This XTS is generated through another code and does not have column names as shown by

dimnames(cor_BG_xts)
[[1]]
NULL
[[2]]
NULL
colnames(cor_BG_xts)
NULL

How can one add column names to xts. I tried searing stack overflow but I get the solutions for data.frame instead of xts. Do, I need to first convert it to df and then name the columns. Also, the xts takes the dates like 1970-01-02 05:30:00. How can one change the xts say 12/1/2009 12:00:00.


Solution

  • Let's first create a reproducible example:

    library(xts)
    
    dates <- seq.Date(as.Date("2018-11-19"), as.Date("2018-11-23"), by = "day")
    numbers <- 1:5
    
    my_xts <- xts(numbers, dates)
    my_xts
                        [,1]
    2018-11-19 05:30:00    1
    2018-11-20 05:30:00    2
    2018-11-21 05:30:00    3
    2018-11-22 05:30:00    4
    2018-11-23 05:30:00    5
    

    Now setting (renaming) a column name is not difficult, either use names, colnames, or setNames.

    names(my_xts) <- "new_column_name"
    # setNames / colnames works as well.
    # my_xts <- setNames(my_xts, "new_column_name")
    # colnames(my_xts) <- "new_column_name"
    # 
    my_xts
                        new_column_name
    2018-11-19 05:30:00               1
    2018-11-20 05:30:00               2
    2018-11-21 05:30:00               3
    2018-11-22 05:30:00               4
    2018-11-23 05:30:00               5
    

    Changing the index format, use indexFormat. You can use any date time format that is mentioned in the details of ?strptime.

    indexFormat(my_xts) <- "%d/%m/%Y %H:%M:%S"
    my_xts
                        new_column_name
    19/11/2018 05:30:00               1
    20/11/2018 05:30:00               2
    21/11/2018 05:30:00               3
    22/11/2018 05:30:00               4
    23/11/2018 05:30:00               5