I have a data frame object test
that has column names:
> test
a b c d e
1 -0.67 -0.02 -0.10 -0.22 -0.32
2 0.46 -1.51 -0.79 0.26 1.19
3 0.22 -0.18 -1.40 0.41 -0.32
4 -2.21 0.79 0.36 1.00 -0.51
5 -0.69 0.39 -0.76 -0.73 -0.43
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. Thanks!
As requested:
> dput(head(a))
structure(list(a = c(-0.67, 0.46, 0.22, -2.21, -0.69, -0.45),
b = c(-0.02, -1.51, -0.18, 0.79, 0.39, -1.33), c = c(-0.1,
-0.79, -1.4, 0.36, -0.76, 0.15), d = c(-0.22, 0.26, 0.41,
1, -0.73, -2.23), e = c(-0.32, 1.19, -0.32, -0.51, -0.43,
-0.58)), .Names = c("a", "b", "c", "d", "e"), row.names = c(NA,
6L), class = "data.frame")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With