将 ts(时间序列)对象转换为 R 中的向量

发布于 2024-08-27 11:46:12 字数 108 浏览 3 评论 0原文

我需要在不接受 ts 对象的向量上使用函数。我正在尝试将其转换为普通的旧向量,但我似乎无法弄清楚。我用谷歌搜索了一下,但大多数人都在尝试将数据类型转换为 ts 对象。我想走另一条路。任何帮助将不胜感激。

I need to use a function on a vector that does not take a ts object. I'm trying to convert it to a plain old vector but I just can't seem to figure it out. I googled around but mostly people are trying to convert data types into ts object. I want to go the other way. Any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泅人 2024-09-03 11:46:13
data(AirPassengers)   # already in your R installation, via package "datasets"
AP = AirPassengers    
class(AP)
# returns "ts"

AP1 = as.numeric(AP)
# returns "numeric"

# another way to do it
AP1 = unclass(AP)

AP1 是一个与 AP 具有相同和长度的向量。该类现在是数字而不是 ts,这在一定程度上意味着索引不再是某种日期时间对象,而只是普通的顺序整数。

因此,对于OP中的具体问题,上面的两个片段中的任何一个都会“将[a ts对象]转换为普通的旧向量”

如果您需要对索引而不是值,或者除了值之外,即从 Date 对象到数字,您可以这样做:

fnx = function(num_days_since_origin, origin="1970-01-01") {
  as.Date(num_days_since_origin, origin="1970-01-01")
}

a = as.Date("1985-06-11")
a2 = as.numeric(a)
# returns: 5640
a3 = fnx(5640)
# returns: "1985-06-11" (a date object)
data(AirPassengers)   # already in your R installation, via package "datasets"
AP = AirPassengers    
class(AP)
# returns "ts"

AP1 = as.numeric(AP)
# returns "numeric"

# another way to do it
AP1 = unclass(AP)

AP1 is a vector with the same values and length as AP. The class is now numeric instead of ts, which means, in part that the indices are no longer some sort of date-time object but just ordinary sequential integers.

So w/r/t the specific question in the OP, either of the two snippets above will "convert [a ts object] to a plain old vector"

If you need to do the same thing with the indices rather than, or in addition to, the values--ie, from Date objects to numeric, you can do that like so:

fnx = function(num_days_since_origin, origin="1970-01-01") {
  as.Date(num_days_since_origin, origin="1970-01-01")
}

a = as.Date("1985-06-11")
a2 = as.numeric(a)
# returns: 5640
a3 = fnx(5640)
# returns: "1985-06-11" (a date object)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文