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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With