【问题标题】:R read.csv from URL error in knitrR从knitr中的URL错误中读取.csv
【发布时间】:2015-03-11 21:09:12
【问题描述】:

当我在 R 控制台中运行此代码时,它运行良好:

read.csv('https://courses.edx.org/c4x/MITx/15.071x_2/asset/WHO.csv')

但是当我尝试放入 R Markdown 文档并编织它时,我得到以下信息:

Error in open.connection(file, "rt") : cannot open the connection
Calls: <Anonymous> ... eval -> read.csv -> read.table -> open -> open.connection
Execution halted

我也尝试过使用httpurl(),但都没有帮助

read.csv('http://courses.edx.org/c4x/MITx/15.071x_2/asset/WHO.csv')
read.csv(url('http://courses.edx.org/c4x/MITx/15.071x_2/asset/WHO.csv'))

两者在通常的 R 会话中都能正常工作。

knitr 怎么做?我希望有办法避免下载文件并将其放在工作目录的某个位置。

出于链接目的:这与read.table() and read.csv both Error in Rmd 中的问题相同,但在我的情况下,我试图从 url 中读取,而不是从文件中读取。

【问题讨论】:

标签: r knitr r-markdown read.table


【解决方案1】:

因此,将@Thomas 的答案调整为您的数据,以下方法可以解决问题。

library(RCurl)
data <- getURL("https://courses.edx.org/c4x/MITx/15.071x_2/asset/WHO.csv",
               ssl.verifypeer=0L, followlocation=1L)
read.csv(text=data)

您还可以查看Error when knitr has to download a zip file,其中删除 https 以获取 http 有帮助。

【讨论】:

    【解决方案2】:

    @puslet88 的回答有所帮助,但我对其稍作修改以减少“侵入性”。 所以我所做的就是在 Rmd 的开头加上以下内容:

    ```{r, echo=FALSE, warning=FALSE, message=FALSE}
    library(RCurl)
    
    read.csv.orig = read.csv
    
    read.csv = function(file, ...) {
      if (is.character(file)) {
        if (grepl('^https://', file)) {
          data = getURL(file, ssl.verifypeer=0L, followlocation=1L)
          return (read.csv.orig(text=data, ...))  
        } else if (grepl('^http://', file)) {
          data = getURL(file)
          return (read.csv.orig(text=data, ...)) 
        } else {
          return (read.csv.orig(file, ...))
        }
      } else {
        return (read.csv.orig(file, ...))
      }
    }
    ```
    

    现在我不必在我的 R markdown 文档中更改所有对 read.csv 的调用,我像以前一样使用它:

    read.csv('https://courses.edx.org/c4x/MITx/15.071x_2/asset/WHO.csv')
    

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多