Search code examples
rtime-series

Refer to time series object by column name


I have the following test data frame :

test <- read.table(header = TRUE, text = "
    a      b      c      d      e
-0.67  -0.02  -0.1   -0.22  -0.32
 0.46  -1.51  -0.79   0.26   1.19
 0.22  -0.18  -1.4    0.41  -0.32
-2.21   0.79   0.36   1.    -0.51
-0.69   0.39  -0.76  -0.73  -0.43
-0.45  -1.33   0.15  -2.23  -0.58
")

In this format, I can easily access the columns using the test$b notation. I can convert this to a time series object without difficulty:

test.ts <- ts(test, frequency=<value>, start=<value>

However, once it's a ts object, is there any easy way to access the columns (or rows) by name instead of by column number? The test.ts object still has the column name information, shown by using colnames:

> colnames(test.ts)
[1] "a" "b" "c" "d" "e"

However, test.ts$b doesn't work. Note that by "easily" I mean without writing something ugly like test.ts[,which(colnames(test.ts)=="b"], because that's not easy, that's ugly. Yes, I could write my own function to do that, but I was wondering whether there's a built-in way to do this.


Solution

  • Use the other subsetting syntax:

    test.ts[, 'b']
    #Time Series:
    #Start = 1 
    #End = 6 
    #Frequency = 1 
    #[1] -0.02 -1.51 -0.18  0.79  0.39 -1.33