循环浏览大块列表 [英] Looping through a list in chunks

查看:51
本文介绍了循环浏览大块列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要通过函数传递的数千个股票代码的列表.但是,该函数一次只能接受200个或更少的符号.我如何设置循环以通过200个符号的块,直到列表完成.下面是一些松散的结构,我认为它可能看起来像.当我通过手动缩短的短符号时,该函数起作用,但是我需要使该过程自动化,以便可以迭代.

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

推荐答案

这是一个可能的快速解决问题的方法:

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
}

代码说明:

  • 通过简单地除以计算块的数量: nSym/chunkSize (我们设上限,因为如果 nSym 不是的倍数,则可能会有余数chunkSize )
  • 对于每个块(1,2,...,n),我们计算相应的开始和结束行索引,如下所示: start =((i-1)* chunkSize + 1) end = min(nSym,(i * chunkSize))( min 函数是必需的,因为最后一个块可能小于 chunkSize )
  • 我们使用索引对原始的 data.frame
  • 进行子集化
  • 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

这篇关于循环浏览大块列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆