views:

245

answers:

1

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.

+5  A: 

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 items in the converted vector (from ts to numeric) represent (depending on what you began with) a total number of days since the epoch (1 Jan 1970), so it's simple to convert the numeric vector back to a ts object:

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)
doug
+1 I love unclass. It is a great way to inspect the contents of an object in R.
Ian Fellows