首先,我会做一些看起来像你描述的东西:
s <- c("AXP", "BA", "DIS")
getSymbols(s, src='yahoo', from='2012-06-19', to='2012-06-20')
L <- lapply(s, function(x) ROC(Cl(get(x)), na.pad=FALSE))
L
[[1]]
AXP.Close
2012-06-20 0.008742843
[[2]]
BA.Close
2012-06-20 0.001233468
[[3]]
DIS.Close
2012-06-20 0.004619916
现在,按列组合结果
do.call(cbind, L)
AXP.Close BA.Close DIS.Close
2012-06-20 0.008742843 0.001233468 0.004619916
这等效于cbind(L[[1]], L[[2]], L[[3]])
但适用于任何长度的列表。
解决您的编辑问题。我认为这将满足您对道指 30 的要求
# make a simple function to get the names of the DJIA components
DJIcomponents <- function() {
require("XML")
djicomp <- readHTMLTable('http://finance.yahoo.com/q/cp?s=^DJI+Components',
stringsAsFactors=FALSE)
data.frame(djicomp[[tail(grep("Symbol", djicomp), 1)]])
}
s <- DJIcomponents()$Symbol
getSymbols(s, src='yahoo', from="2009-06-20", to="2009-06-22")
out <- do.call(cbind, lapply(s, function(sym) {
sum(getDividends(sym, from = "2008-06-29", to="2009-06-20"))/Cl(get(sym, pos=.GlobalEnv))
}))
现在,按降序排列
out[1, order(out[1, ], decreasing=TRUE)]
GE.Close BAC.Close PFE.Close DD.Close T.Close
2009-06-22 0.08940972 0.08207705 0.07572684 0.06804979 0.06708075
MRK.Close VZ.Close AA.Close CAT.Close CVX.Close
2009-06-22 0.06036537 0.06029314 0.05389222 0.05191595 0.03953771
HD.Close JPM.Close INTC.Close MMM.Close BA.Close
2009-06-22 0.03870968 0.03620322 0.03571429 0.03514877 0.03496802
KFT.Close JNJ.Close KO.Close MCD.Close PG.Close
2009-06-22 0.03445545 0.03369977 0.03292353 0.03277972 0.03243671
AXP.Close TRV.Close UTX.Close XOM.Close MSFT.Close
2009-06-22 0.0309944 0.02922552 0.02805249 0.02353283 0.02147766
WMT.Close IBM.Close DIS.Close HPQ.Close CSCO.Close
2009-06-22 0.02103313 0.01961347 0.01544572 0.008479067 0