英文:
a loop function in R
问题
目前有以下几行代码,并希望编写一个循环函数来减少代码行数:
使用一个数据集的示例要下载:
library(quantmod)
start_date="2013-01-01"
end_date="2014-01-01"
AAPL<-getSymbols("AAPL",from=start_date,to=end_date,auto.assign = FALSE)
AAPL_ret<-apply(AAPL[,6],2,diff)
当我尝试下面的函数来完成工作:
test_function<-function(ticker){
x<-getSymbols(ticker, from=start_date,to=end_date,auto.assign = FALSE)
x_ret<-apply(x[,6],2,diff)
plot(x_ret)
}
然而,在需要下载多个数据集的情况下,是否更可行编写一个for循环函数呢?例如,如果有一系列需要下载数据的股票代码:
test_list<-c("AAPL","TSLA","TGT")
我能否将上面的test_function
函数改写为循环遍历test_list
中的股票代码?
谢谢。
英文:
currently have below lines n would like to write a loop function to reduce lines:
example with one dataset to be downloaded:
library(quantmod)
start_date="2013-01-01"
end_date="2014-01-01"
AAPL<-getSymbols("AAPL",from=start_date,to=end_date,auto.assign = FALSE)
AAPL_ret<-apply(AAPL[,6],2,diff)
n I try to below function to do the work:
test_function<-function(ticker){
x<-getSymbols(ticker, from=start_date,to=end_date,auto.assign = FALSE)
x_ret<-apply(x[,6],2,diff)
plot(x_ret)
}
However, in the case where I have more than one set of data to be downloaded, is it more feasible to write a for loop function? Say if there are a list of tickers which I need to download data:
test_list<-c("AAPL","TSLA","TGT")
Can I transform the test_function above to loop thru the ticker in test_list?
Thanks.
答案1
得分: 1
One approach would be to wrap the function in Vectorize
, which will allow it to accept a vector input:
test_function <- Vectorize(function(ticker) {
x <- getSymbols(ticker,
from = start_date,
to = end_date,
auto.assign = FALSE)
x_ret <- apply(x[, 6], 2, diff)
plot(x_ret, main = ticker)
})
Then when you run test_list
through, it will plot each one (below, I am changing the layout to plot all three for visualization purposes):
test_list <- c("AAPL","TSLA","TGT")
par(mfrow = c(2, 2))
test_function(test_list)
英文:
One approach would be to wrap the function in Vectorize
, which will allow it to accept a vector input:
test_function <- Vectorize(function(ticker) {
x <- getSymbols(ticker,
from = start_date,
to = end_date,
auto.assign = FALSE)
x_ret <- apply(x[, 6], 2, diff)
plot(x_ret, main = ticker)
})
Then when you run test_list
through, it will plot each one (below, I am changing the layout to plot all three for visualization purposes):
test_list <- c("AAPL","TSLA","TGT")
par(mfrow = c(2, 2))
test_function(test_list)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论