简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM