一个在R中的循环函数

huangapple go评论58阅读模式
英文:

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=&quot;2013-01-01&quot;
end_date=&quot;2014-01-01&quot;

AAPL&lt;-getSymbols(&quot;AAPL&quot;,from=start_date,to=end_date,auto.assign = FALSE)
AAPL_ret&lt;-apply(AAPL[,6],2,diff)

n I try to below function to do the work:

test_function&lt;-function(ticker){
  x&lt;-getSymbols(ticker, from=start_date,to=end_date,auto.assign = FALSE)
  x_ret&lt;-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&lt;-c(&quot;AAPL&quot;,&quot;TSLA&quot;,&quot;TGT&quot;)

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)

一个在R中的循环函数

英文:

One approach would be to wrap the function in Vectorize, which will allow it to accept a vector input:

test_function &lt;- Vectorize(function(ticker) {
  x &lt;- getSymbols(ticker,
               from = start_date,
               to = end_date,
               auto.assign = FALSE)
  x_ret &lt;- 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 &lt;- c(&quot;AAPL&quot;,&quot;TSLA&quot;,&quot;TGT&quot;)

par(mfrow = c(2, 2))
test_function(test_list)

一个在R中的循环函数

huangapple
  • 本文由 发表于 2023年6月29日 04:38:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定