Search code examples
rxts

xts format assign name for index column


I have a xts file format which when reading didn't have a name for the index column, see below. How do I assign a name to it? Ideally, I wanted to use the date time field for plotting at subsequent stages. Thanks.

                    Elapsed Time Total Inflow Total Evap Surface Infil
2021-04-30 10:02:00        0.033            0      0.125             0
2021-04-30 10:04:00        0.067            0      0.125             0
2021-04-30 10:06:00        0.100            0      0.125             0
2021-04-30 10:08:00        0.133            0      0.125             0
2021-04-30 10:10:00        0.167            0      0.125             0
2021-04-30 10:12:00        0.200            0      0.125             0

Solution

  • We assume that the question is asking how to plot an xts object such as x in the Note at the end.

    There are numerous plotting functions for zoo and xts objects (every xts object is also a zoo object) so it is unnecessary to convert it to a data frame (although in the last example below we show this.) All the facilities of each of these plotting systems are available when using this. Also shown below is how to specify the x label in each case.

    library(xts)  # this also pulls in zoo
    
    # classic graphics
    plot(as.zoo(x), xlab = "Time")
    
    # lattice graphics
    library(lattice)
    xyplot(x, xlab = "Time")
    
    ## ggplot2 graphics
    library(ggplot2)
    autoplot(x) + xlab("Time")
    
    # convert to data frame and then use matplot
    d <- fortify.zoo(x)
    matplot(d[[1]], d[-1], xlab = "Time")
    

    Note

    Lines <- "                 Elapsed Time  Total Inflow  Total Evap  Surface Infil
        2021-04-30 10:02:00        0.033            0      0.125             0
        2021-04-30 10:04:00        0.067            0      0.125             0
        2021-04-30 10:06:00        0.100            0      0.125             0
        2021-04-30 10:08:00        0.133            0      0.125             0
        2021-04-30 10:10:00        0.167            0      0.125             0
        2021-04-30 10:12:00        0.200            0      0.125             0"
    
    # split into lines, trim whitespace off ends, replace 2+ spaces w comma
    L <- Lines |>
      textConnection() |>
      readLines() |>
      trimws() |>
      gsub(pattern = "  +", replacement = ",")
    
    z <- read.csv.zoo(text = L, index = 0, tz = "", check.names = FALSE)
    x <- as.xts(z)