user5948364
user5948364

Reputation:

Looping through a list in chunks

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,]

Upvotes: 2

Views: 1521

Answers (1)

digEmAll
digEmAll

Reputation: 57210

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

Upvotes: 3

Related Questions