Skip to content

Most common way to add derived columns to an XTS object?

5 messages · Jeff Ryan, Joshua Ulrich, Robert Nicholson

#
So you have data in your XTS object and all I'm trying to do is add columns (attributes) that are derived values.

does anybody have an example of this?

I'm trying to perform a simply transformation on an existing attribute in my XTS object and store the value as a new attribute.
#
Hi Robert,

New columns aren't attributes, they are columns.  For that:
x  y
2010-03-11  1  2
2010-03-12  2  4
2010-03-13  3  6
2010-03-14  4  8
2010-03-15  5 10
2010-03-16  6 12
2010-03-17  7 14
2010-03-18  8 16
2010-03-19  9 18
2010-03-20 10 20


HTH,
Jeff

On Wed, Mar 10, 2010 at 7:52 AM, Robert Nicholson
<robert.nicholson at gmail.com> wrote:

  
    
#
You already asked and received an answer for this question.  I also
answered you when you asked me this question off-list.  Please don't
post duplicate questions, especially when they were answered only days
ago!

As Jeff Ryan said, use merge.xts.  See ?merge.xts.

x <- .xts(1:10,1:10)
y <- merge(x,d=diff(x))

As I said, use "$<-".  See ?"$".
y$r <- rnorm(NROW(y))

Do some work.  No one is going to spoon feed you.

--
Joshua Ulrich
FOSS Trading: www.fosstrading.com



On Wed, Mar 10, 2010 at 7:52 AM, Robert Nicholson
<robert.nicholson at gmail.com> wrote:
#
The previous post was when I had something given to me already as in

library('quantmod')
getSymbols('AAPL')
CHANGE = rollapply(Cl(AAPL),width=2, function(x) log(x[2]/x[1]), by=1, align = "right", na.pad = TRUE)
merge.zoo(AAPL, CHANGE)

and this worked fine

however

I'm not using rollapply and simply want to iterate over my existing XTS object and create a new column
with a derived value.

I was trying

SD = rollapply(CHANGE, width=20, function(x) sd(x) * sqrt(252), by=1, align = "right", na.pad = TRUE)
colnames(SD) = "StdDev Log Change"
for (i in 1:NROW(SD)) {
SD[i, "STDEV"] = SD[i, "StdDev Log Change"] * Cl(AAPL)[i];
}

but it wasn't working

I'm sorry if you thought it was a duplicate question. In my mind the context where I was trying to perform
the change was different because in the original case some other function built me a series that I then
merged with my original. My question was how to I go about modifying the original without generating
a new series and merging.

In this case I'm iterating because I'm trying to perform a transformation where I map to another series
using the same index.
On Mar 10, 2010, at 8:12 AM, Joshua Ulrich wrote:

            
#
It seems the missing piece in the puzzle was to define the column first with

SD$STDDEV = rep(0, NROW(SD))
for (i in 1:NROW(SD)) {
SD[i, "STDDEV"] = SD[i, "StdDev Log Change"] * Cl(AAPL)[i];
}

then I can expect to assign values to it.
On Mar 10, 2010, at 8:12 AM, Joshua Ulrich wrote: