Функция ddply
в пакете plyr
обычно делает эту операцию безболезненной (но она может быть медленной для больших наборов данных).
# Sample data
library(quantmod)
d <- NULL
for(s in c("^GSPC","^N225")) {
tmp <- getSymbols(s,auto.assign=FALSE)
tmp <- Ad(tmp)
names(tmp) <- "price"
tmp <- data.frame( date=index(tmp), id=s, price=coredata(tmp) )
d[[s]] <- tmp
}
d <- do.call(rbind, d)
rownames(d) <- NULL
# Sample computations: lag the prices and compute the logarithmic returns
library(plyr)
d <- ddply(
d, "id",
mutate,
previous_price = lag(xts(price,date)),
log_return = log(price / previous_price)
)