How do I check the existence of a downloaded file

R

R Problem Overview


I've created a R markdown file that starts by loading a file from the web. I found the cache=TRUE to be a little flaky so I want to put an if condition in to check for the downloaded file before downloading it.

Current Code - Always downloads file

fileURL <- "https://dl.dropbox.com/u/7710864/courseraPublic/samsungData.rda"
setInternet2(TRUE)
download.file(fileURL ,destfile="./data/samsungData.rda",method="auto")
load("./data/samsungData.rda")

Desired Code - only upload if if not already downloaded

 destfile="./data/samsungData.rda"    
 fileURL <-
 "https://dl.dropbox.com/u/7710864/courseraPublic/samsungData.rda"   
 if (destFile doesNotExist) {
    setInternet2(TRUE)
    download.file(fileURL ,destfile,method="auto") }
    load("./data/samsungData.rda")
 }
 load(destfile)

What syntax will give me the condition "destFile doesNotExist"

R Solutions


Solution 1 - R

You can use tryCatch

  if(!file.exists(destfile)){
    res <- tryCatch(download.file(fileURL,
                              destfile="./data/samsungData.rda",
                              method="auto"),
                error=function(e) 1)
    if(dat!=1) load("./data/samsungData.rda") 
}

Solution 2 - R

As per the answer given by @agstudy

 destfile="./data/samsungData.rda" 
 fileURL <-
 "https://dl.dropbox.com/u/7710864/courseraPublic/samsungData.rda"   
 if (!file.exists(destfile)) {
    setInternet2(TRUE)
    download.file(fileURL ,destfile,method="auto") }
    load("./data/samsungData.rda")
 }
 load(destfile)

Solution 3 - R

An easy way to check the existence of a file in your working directory is: which(list.files() == "nameoffile.csv")

This doesn't exactly answer his question but I thought this might be helpful to someone who simply wants to check if a particular file is there in their directory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1605665View Question on Stackoverflow
Solution 1 - RagstudyView Answer on Stackoverflow
Solution 2 - Ruser1605665View Answer on Stackoverflow
Solution 3 - RNutanView Answer on Stackoverflow