Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a folder inside a function

Tags:

directory

r

So I want to use R to automatically create a folder for the dataset that I happen to be analyzing. Due to laziness, a function is being written to create this folder, analyze the data, and store results into that folder so that they can be looked at later on.

Now if I try to use the aircraft data from library(robustbase):

setwd("C:/Users/Admin/Desktop/")
analysis<-function(dataset,other_bit_and_pieces){
paste("dir.create(",dataset,")",sep="")
}

analysis(aircraft)

I get either an error message saying that aircraft does not exist, or (if I load the library), it spits out "dir.create(c( all the data from aircraft))"

How should I be writing this so that a new folder is created with the dataset names every time I change dataset?

like image 670
Albort Avatar asked Dec 01 '25 09:12

Albort


2 Answers

The general R idiom for this is deparse(substitute(....)).

analysis <- function(object, create = FALSE){
  dirname <- deparse(substitute(object))
  if(create) {
      dir.create(dirname)
  }
  dirname
}

> mydata <- data.frame(x=1:10)
> analysis(mydata)
[1] "mydata"

Note that I changed the function to not create the dir automagically, in case people are testing and this clobbers an existing dir. To show it is working, I get it to return the dirname. In practice you won't need anything from the if() onwards.

like image 110
Gavin Simpson Avatar answered Dec 02 '25 22:12

Gavin Simpson


From what I can understand something like the following will work

mydata <- data.frame(x=1:10)

analysis <- function(object){
  dir.create(as.character(as.list(match.call())[2]))
}

analysis(mydata)
# will create a directory 'mydata' as a subdirectory of the current working directory.

Look at ?match.call for how this works!

like image 30
mnel Avatar answered Dec 02 '25 21:12

mnel