2

I have a list of several thousand stock symbols to pass through a function. However the function only accepts 200 or less symbols at a time. How do i set up the loops to pass through chunks of 200 symbols until the list is complete. Below is some loose structure i think it may look like. The function works when I pass through the manually shortened shortsymb, but I need to automate this process so it can iterate.

library(quantmod)
symbols<-read.csv("companylist.csv")

for(i in 1:end){
  for(i in 1:200)

      metrics <- getQuote(paste(symbols sep="", collapse=";"), what=what_metrics)
}}

shortsymb<-symbols[1:199,]
  • Hi, welcome to SO. Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It makes it easier for others to help you. – Heroka Mar 19 '16 at 16:59

1 Answers1

3

Here's a possible quick'n'dirty solution:

nSym <- nrow(symbols)
chunkSize <- 200
for(i in 1:ceiling(nSym / chunkSize)){  
  shortsymb<-symbols[((i-1)*chunkSize+1):min(nSym,(i*chunkSize)),]
  # do what you need with shortsymb
}

Description of the code:

  • compute the number of chunks by simply dividing: nSym / chunkSize (we take the ceiling since there can be a remainder, if nSym is not multiple of chunkSize)
  • for each chunk (1,2,...,n) we compute the corresponding start and end row indexes, as start = ((i-1)*chunkSize+1) and end = min(nSym,(i*chunkSize)) (min function is necessary because last chunk might be smaller than chunkSize)
  • we use the indexes to subset the original data.frame
digEmAll
  • 56,430
  • 9
  • 115
  • 140