73

Possible Duplicate:
Automatically Delete Files/Folders in R

I would like to know if there is a way in R to check up if a file is in my current directory, and if it is there then the program deletes it?

I know that other languages have direct access to OS functions to do this task, but I am a little bit dubious if R has that capability.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Layla
  • 5,234
  • 15
  • 51
  • 66

2 Answers2

173

How about:

#Define the file name that will be deleted
fn <- "foo.txt"
#Check its existence
if (file.exists(fn)) {
  #Delete file if it exists
  file.remove(fn)
}

As far as I know, this is a permanent, non-recoverable (i.e. not "move to recycle bin") on all platforms ...

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 1
    Any alternative that moves files to recycle bin/trash? – duncanrager Jun 18 '19 at 14:35
  • @duncanrager, I don't know of one. You could ask a new question (after checking for other answers on StackOverflow, of course ...) – Ben Bolker Jun 19 '19 at 07:41
  • 1
    Stupid question: how are you able to execute the if() condition without the requisite {}? – ChinG Jun 11 '20 at 02:09
  • 1
    curly brackets are not required if the code to be executed consists of a single statement (although arguably it would be best practice to include them anyway) – Ben Bolker Jun 11 '20 at 14:12
  • @derp92 Just to confirm. `file.remove(fullfilepath)` permanently deletes the file. – Jason Nov 06 '20 at 06:01
21

One of the reasons R cannot be safely exposed to outside users is that it offers complete access to system facilities. In addition to the list.files, list.dirs and the file.remove functions, the system function allows access to pretty much any exploit imaginable.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 2
    I think the downvotes (not necessarily from @DWin) are because it shouldn't have been *too* hard to find these answers by googling/searching Stack Overflow. I don't actually think the link pointed to (which you would have found by searching SO for `[r] delete file`) is an exact duplicate, but it probably would have answered your question. – Ben Bolker Jan 08 '13 at 17:07
  • 1
    @BenBolker. A question gets closed as a duplicate i it cover the same material. The functions in your answer all appear immediately if one types `?files` at the command prompt. No googling needed. I suspect the downvotes are due both to the lack of any statement that a search of any sort was done and to the implied slur at R being limited in some way. – IRTFM Jan 08 '13 at 18:19