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?
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With