开发者

Converting a ts (Time Series) object to a Vector in R

开发者 https://www.devze.com 2022-12-25 11:32 出处:网络
I need to use a function on a vector t开发者_StackOverflowhat 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 m

I need to use a function on a vector t开发者_StackOverflowhat 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号