Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scale columns of an xts object

I often deal with data in xts formats, and frequently must scale them (say to be equal to 100 on some date). I presently do this using a function, which works using a for-loop -- however this does not seem very functional.

Here's how i do it now:

df1 <- data.frame(rnorm(100), runif(100), 1:100*rnorm(100))
dfx <- xts(df1, order.by = seq(as.Date("2001-01-01"), by='mon', length.out=100))

dfxColScl <- function(dfrm, pos=1, idx = 100)
{
    scaledDF <- dfrm
    for (i in 1:ncol(dfrm)) {
        scaledDF[, i] <- dfrm[,i] / as.numeric(dfrm[pos, i]) * idx
    }
    return(scaledDF)
}

Is there some clever apply type function that is the R way to do this?

like image 912
ricardo Avatar asked Jun 03 '13 19:06

ricardo


1 Answers

sweep can be used to divide a matrix by a row.

dfx.scaled2 <- sweep(100*dfx, 2, dfx[1], "/")
all.equal(dfx.scaled, dfx.scaled2) # same result as @Joshua
#[1] TRUE
like image 136
GSee Avatar answered Sep 24 '22 05:09

GSee