11

I want to extract the numerical values of a xts object. Let's look at an example

data <- new.env()
starting.date <- as.Date("2006-01-01")
nlookback <- 20
getSymbols("UBS", env = data, src = "yahoo", from = starting.date)
Reg.curve <- rollapply(Cl(data$UBS), nlookback, mean, align="right")

The Reg.cuve is still a xts object but actually I'm just interested in the running means. How can I modify Reg.curve to get a numerical vector?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
math
  • 1,868
  • 4
  • 26
  • 60

2 Answers2

19

Use coredata:

reg.curve.num <- coredata(Reg.curve)
# or, if you want a vector:
reg.curve.num <- drop(coredata(Reg.curve))
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • Is there a reason to prefer `drop(coredata(Reg.curve))` over `as.numeric(Reg.curve)`? – GSee Apr 05 '14 at 13:45
  • @GSee: the former doesn't assume/coerce the result to numeric, so it's more general. It works whether `Reg.curve` is numeric, integer, logical, character, etc. – Joshua Ulrich Apr 05 '14 at 15:10
  • I wish there was a column that included the time indices. – EngrStudent Oct 24 '19 at 15:50
  • @EngrStudent: the time indices are in the `index` attribute. You can access it with `index(Reg.curve)`. It can't be a column because xts/zoo objects are matrices and therefore can only contain one data type (i.e. they can't have a Date column and a numeric column). – Joshua Ulrich Jul 28 '23 at 13:53
1

To extract the numerical values of any xts, ts, or zoo object use:

as.numeric(Reg.curve)
desertnaut
  • 57,590
  • 26
  • 140
  • 166
mpetric
  • 103
  • 7