2016-02-09 88 views
1

我從雅虎提取15個符號的ETF數據,並且即將編寫相同的代碼行15次。我讀過lapply,但在這方面我沒有把握。在沒有函數的情況下在R中使用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 

我的目標是與包含各行中的所有符號列標題,並計算出返回一組數據來完成。

回答

0

你被允許在lapply一拉

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]) 
+0

每當我試圖用lapply找到廣告我得到這個錯誤(調整)的價格列FUN參數來定義一個匿名函數:錯誤在廣告中: 下標越界:沒有包含「已調整」的列名稱 –

+0

廣告(ACWI)正常工作。但引號失敗,並失敗as.name。 –

+0

@KennethK。請參閱更新。我忘記了'quantmod'是一個很奇怪的包;使用'auto.assign'選項使其表現得更像普通包(這樣我們可以使用'var_name < - getSymbols(「IJR」)''將'xts'對象分配給'var_name'而不是創建變量'IJR'在環境中,當前的默認值,這幾乎不可能用編程方式來編寫)。另一種方法是運行'Ad(get(getSymbols(s)))',但這會混亂你的名字空間。 – MichaelChirico

相關問題