Why do I need to use mode = wb with download.file() for this .rds file?

时间:2015-04-23 05:25:15

标签: r download

I was getting hung up on Shiny Apps Tutorial Lesson 5 because I was unable to open the counties.rds file. readRDS() threw: error reading from connection.

I figured out I could open the .rds fine if I downloaded it with download.file(URL, dest, mode = "wb") or simply used my browser to download the file to my local directory.

Outstanding Question: Why does the counties.rds file not open properly if I use download.file() without setting mode = "wb"? I expect the answer will be something obvious like: "Duh, counties.rds is a binary file." However, before I try to answer my own question, I'd like confirmation from someone with more experience.

Repro steps:

    download.file("http://shiny.rstudio.com/tutorial/lesson5/census-app/data/counties.rds",
    "counties.rds")

    counties <- readRDS("counties.rds")
    Error in readRDS("counties.rds") : error reading from connection

Resolution: Download via browser or use binary mode (wb).

    download.file("http://shiny.rstudio.com/tutorial/lesson5/census-app/data/counties.rds",
    "counties.rds", mode = "wb")
    counties <- readRDS("counties.rds") # Success!

1 个答案:

答案 0 :(得分:1)

我的建议是始终指定'模式',并始终使用mode =“wb”非常安全。我认为后者应该是默认值,并且文件扩展名的自动识别是错误的,不应该依赖,参见https://stat.ethz.ch/pipermail/r-devel/2012-August/064739.html