5

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?

4

2 回答 2

4

sweep可用于将矩阵除以行。

dfx.scaled2 <- sweep(100*dfx, 2, dfx[1], "/")
all.equal(dfx.scaled, dfx.scaled2) # same result as @Joshua
#[1] TRUE
于 2013-06-03T23:27:46.673 回答
3

你可以使用apply.daily. 请注意,您仍然必须coredata在要除以的行上使用,因为 xts/zoo 操作在执行操作之前总是按索引对齐。

dfx.scaled <- apply.daily(dfx, function(x) x/coredata(dfx[1,])*100)
于 2013-06-03T19:32:34.390 回答