3

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?

1
  • 1
    Albort, that's not laziness. That's intelligence: make the software do boring, repetitive tasks for you! Commented Sep 11, 2012 at 11:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.