Charmgoggles Charmgoggles - 3 months ago 17
R Question

when downloading or saving a file in r I can't make R create a directory

Whenever I want to download something to a folder, I have to create the folder manually first.
for instance:


Will give me an error

cannot open destfile 'data2/portal_data_joined.csv', reason 'No such file or directory'

My solution is to manually create a folder data2 and then it works.
My question is: Why doesn't R have the right to create a folder?


R has the right, but it chooses not to. It would seem to be fairly common practice to not create folders when R makes a file:

> write.table(x,file="./foo/bar/baz.csv")
Error in file(file, ifelse(append, "a", "w")) : 
  cannot open the connection
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
  cannot open file './foo/bar/baz.csv': No such file or directory

A neat solution is to create a function, here called makepath, that creates the folder at any depth and returns the path back:

> makepath = function(path){dir.create(dirname(path),recursive=TRUE);path}

Then you can do:

> write.table(x,file=makepath("./foo/bar/baz.csv"))
> write.table(x,file=makepath("./foo/bar/qux/moo/baz.csv"))

And similarly for download.file in your case.