【问题标题】:R Text data scraper loop through datesR文本数据刮板循环通过日期
【发布时间】:2020-05-14 10:04:37
【问题描述】:

我正在做一个小项目,目标是从网站检索文本格式的数据。 (http://regsho.finra.org/regsho-Index.html)

网站很好,可以在线提供,但他们在不同的链接中对数据进行了几天的排序

我想过循环使用日期并使用以下代码存储数据:

#Download the needed data

my_data <- c()

for (i in 01:13){

my_data <- read.delim(sprintf("http://regsho.finra.org/CNMSshvol202005%i.txt", i), header=TRUE, sep="|")

}

head(my_data)

这里的问题是在行

for (i in 01:13){ # The date in the website is 01-02-03 and the loop seems to ommit the 0

我使用了 sprintf() 方法,因此我可以在字符串中包含一个变量。

这一行空变量 my_data 似乎总是被最后下载的数据覆盖。

my_data <- read.delim(sprintf("http://regsho.finra.org/CNMSshvol202005%i.txt", i), header=TRUE, sep="|")  
# the empty variable my_data always seems to be overwritten by the last data downloaded. 

如果我正朝着正确的方向前进,有人可以向我保证,因为我开始怀疑自己在这里

任何帮助将不胜感激!

提前致谢

【问题讨论】:

  • 01:13 不考虑“0”,但它与1:13 相同,因为它是数字。你需要有一个 srtring 所以试试下面试试 stringr::str_pad(1:13, 2, "left", "0")
  • 第二个问题,请尝试my_data &lt;- rbind(mydata, read.delim(...) )
  • 看起来并不是每个日期都有数据,例如缺少 2、3 和 10。其他月份也缺少几天。您最好只抓取链接。

标签: r loops web-scraping lapply


【解决方案1】:

这应该会给你一个前导 0 而不使用额外的包:

sprintf("%02d", i)

即

sprintf("http://regsho.finra.org/CNMSshvol202005%02d.txt", i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2012-10-29
    相关资源
    最近更新 更多