Daniel Fletcher
Daniel Fletcher

Reputation: 1244

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

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!

Upvotes: 1

Views: 4657

Answers (1)

HenrikB
HenrikB

Reputation: 6815

My suggestion is to always specify 'mode' regardless and that it pretty safe to always use mode="wb". I argue it the latter should be the default and that the automatic recognition by file extension is faulty and should not be relied upon, cf. https://stat.ethz.ch/pipermail/r-devel/2012-August/064739.html

Upvotes: 1

Related Questions