6

I'm new to R and i have question about using file.exist.

I tried:

if(!file.exist("data")){
    dir.create("data")
}

But I get the error, could not find function "file.exist".

I then tried:

if (is!TRUE(file.exists("data"))) {
     dir.create("data")
}

I still get an error, unexpected '!' in "if (is!". But it creates the folder.

What am I doing wrong?

hIlary
  • 85
  • 1
  • 9
  • `file.exist` is different than `file.exists`. I don't really know what made you think `is!TRUE` is a function but it isn't. – Dason Sep 13 '18 at 17:22
  • 1
    Possible duplicate of [How do I check the existence of a local file](https://stackoverflow.com/questions/14904983/how-do-i-check-the-existence-of-a-local-file) – help-info.de Sep 13 '18 at 17:23
  • 1
    Welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour) and read through the [help center](http://stackoverflow.com/help), in particular how to ask. Your best bet here is to do your research, search for related topics on SO, and give it a go. After doing more research and searching, post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) of your attempt and say specifically where you're stuck, which can help you get better answers. – help-info.de Sep 13 '18 at 17:24

2 Answers2

7

Your are looking for the following:

if(!dir.exists("data")) {
    dir.create("data")
}

Here are some Links that might help you on the way:

Boolean Operators

files2 package for file system interfacing

darian_
  • 71
  • 3
  • Note that `file.exists` will detect directories, but it will also detect files. `dir.exists` is the most ideal here, good suggestion! – Badger Sep 13 '18 at 17:33
2

While this is potentially a duplicate, I think it's worth a little explanation for you.

if(!file.exists("data")){
    dir.create("data")
}

This is the right way to go about it, you've done that well. Your issue is R doesn't know where "data" lives if you've not set the working directory to the location that data would or wouldn't exist. 2 ways to tackle this: 1:

setwd("C:/folder/folder/folder/data_location")
if(!file.exists("data")){
    dir.create("data")
}

2:

if(!file.exists("C:/folder/folder/folder/data_location/data")){
   dir.create("data")
}

Something else I've noticed is you're looking for a file, then creating a directory. If you're interested in a directory, check out dir.exists.

Hope this helps!

Badger
  • 1,043
  • 10
  • 25