没有函数时在 R 中使用 lapply?
Using lapply in R when there isn't a function?
我正在从 Yahoo 提取 15 个交易品种的 ETF 数据,并且即将编写相同的代码行 15 次。我已经阅读了 lapply
但在这种情况下我没能理解它。
加载我的 getSymbols
文件后,我开始编写下面前两个符号的代码,但会复制粘贴,然后更改符号,共 15 次。我知道必须有一种方法可以用 lapply
或类似的东西来完成这些步骤...
library(quantmod)
library(tseries)
library(PerformanceAnalytics)
library(xts)
library(timeSeries)
library(TTR)
#load asset class symbols and data
loadSymbolLookup(file="assetclassymbols.rda")
getSymbols(c("ACWI","ITOT","IJR","EFA","EEM","AGG","MUB","TIP","TLH","TLT","HYG","EMB","IYR","GSG","GLD"))
#pull adjusted close value for a specific time period
ACWI.adj=Ad(ACWI)['2015-12-31::2016']
AGG.adj=Ad(AGG)['2015-12-31::2016']
#REPEAT FOR EACH SYMBOL
#calculate returns for the specific time period and remove prior-period "NA" row
ACWI.return=Return.calculate(ACWI.adj)
AGG.return=Return.calculate(AGG.adj)
ACWI.return=ACWI.return[-c(1)]
AGG.return=AGG.return[-c(1)]
#REPEAT FOR EACH SYMBOL
#merge asset class return streams to a single dataset
asset.returns=(merge(ACWI.return,AGG.return)) #...CONT. MERGING ALL SYMBOLS.return
colnames(asset.returns)=c("ACWI","AGG") #...CONT. LIST OF ALL SYMBOLS
我的目标是完成一个包含所有符号的数据集作为第 headers 列,并在每一行中计算 returns。
您可以在 lapply
的 FUN
参数中定义匿名函数,a la
syms <- c("ACWI","ITOT","IJR","EFA","EEM","AGG","MUB",
"TIP","TLH","TLT","HYG","EMB","IYR","GSG","GLD")
lapply(syms, function(s)
Return.calculate(Ad(getSymbols(s, auto.assign = FALSE)
)['2015-12-31::2016'])[-1L])
我正在从 Yahoo 提取 15 个交易品种的 ETF 数据,并且即将编写相同的代码行 15 次。我已经阅读了 lapply
但在这种情况下我没能理解它。
加载我的 getSymbols
文件后,我开始编写下面前两个符号的代码,但会复制粘贴,然后更改符号,共 15 次。我知道必须有一种方法可以用 lapply
或类似的东西来完成这些步骤...
library(quantmod)
library(tseries)
library(PerformanceAnalytics)
library(xts)
library(timeSeries)
library(TTR)
#load asset class symbols and data
loadSymbolLookup(file="assetclassymbols.rda")
getSymbols(c("ACWI","ITOT","IJR","EFA","EEM","AGG","MUB","TIP","TLH","TLT","HYG","EMB","IYR","GSG","GLD"))
#pull adjusted close value for a specific time period
ACWI.adj=Ad(ACWI)['2015-12-31::2016']
AGG.adj=Ad(AGG)['2015-12-31::2016']
#REPEAT FOR EACH SYMBOL
#calculate returns for the specific time period and remove prior-period "NA" row
ACWI.return=Return.calculate(ACWI.adj)
AGG.return=Return.calculate(AGG.adj)
ACWI.return=ACWI.return[-c(1)]
AGG.return=AGG.return[-c(1)]
#REPEAT FOR EACH SYMBOL
#merge asset class return streams to a single dataset
asset.returns=(merge(ACWI.return,AGG.return)) #...CONT. MERGING ALL SYMBOLS.return
colnames(asset.returns)=c("ACWI","AGG") #...CONT. LIST OF ALL SYMBOLS
我的目标是完成一个包含所有符号的数据集作为第 headers 列,并在每一行中计算 returns。
您可以在 lapply
的 FUN
参数中定义匿名函数,a la
syms <- c("ACWI","ITOT","IJR","EFA","EEM","AGG","MUB",
"TIP","TLH","TLT","HYG","EMB","IYR","GSG","GLD")
lapply(syms, function(s)
Return.calculate(Ad(getSymbols(s, auto.assign = FALSE)
)['2015-12-31::2016'])[-1L])