本文介绍了按列名引用时间序列对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有列名的数据框对象 test:

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

在这种格式中,我可以使用 test$b 符号轻松访问列.我可以毫不费力地将其转换为时间序列对象:

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>

但是,一旦它是一个 ts 对象,是否有任何简单的方法可以按名称而不是按列号访问列(或行)?test.ts 对象仍然有列名信息,使用colnames 表示:

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"

然而,test.ts$b 不起作用.请注意,轻松"是指不写像 test.ts[,which(colnames(test.ts)=="b"] 这样难看的东西,因为这并不容易,那很丑陋.是的,我可以编写自己的函数来做到这一点,但我想知道是否有内置的方法来做到这一点.谢谢!

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!

根据要求:

> 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")

推荐答案

使用其他子集语法:

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

这篇关于按列名引用时间序列对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 03:22