76

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"

sk8forether
  • 247
  • 2
  • 9
user1605665
  • 3,771
  • 10
  • 36
  • 54

3 Answers3

82

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") 
}
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • Right, I have not got right the code the first time. However, you are loading the file only in the case that is has been downloaded, not in the case when it was downloaded already - i.e. it's not what OP was asking for. Also, the code is not working due to typos and contain twice a string that is already saved in a variable. What a stupid downvote. – Kamil S Jaron Jul 06 '18 at 07:19
  • 16
    `file.exists` (or `!file.exists`) seems to be the real magic here, since that's what the OP asked for. – Dannid Nov 07 '18 at 17:59
  • What is `dat` doing? – not2qubit Nov 21 '20 at 14:01
26

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)
user1605665
  • 3,771
  • 10
  • 36
  • 54
  • 7
    it is not necessary to include the `load(".data/samsungData.rda")` in the conditional block, as you're loading it twice if the file didn't exist. – hugovdberg Jun 18 '16 at 10:25
12

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.

Nutan
  • 320
  • 2
  • 7
  • 1
    I found this variation of your answer to work well TRUE %in% (list.files() == 'nameoffile.csv') -- using which sometimes returns a integer and sometimes a vector, where this always returns a boolean. – Kem Mason Jan 24 '19 at 20:47