0

I have a function in R that I need to conditionally load a .rda file. For example, I want the user of the function to be able to specify which file they want loaded, and then R will load the corresponding datafile.

The function takes two arguments, the state (i.e. "NY") and the .rda file I want it to load, (i.e. "data_0203.rda".

Because there aren't that many .rda files in the pool that I need to read from, I figured one way was just to do if statements, like the following.

if(datafile=="data_9091"||datafile=="data_9091.rda")
{load("/Users/blahblahblah/data_9091.rda")
state.in=as.data.frame(data_9091[[which(names(data_9091)==(tolower(state)))]][1])
state.out=as.data.frame(data_9091[[which(names(data_9091)==(tolower(state)))]][2]})

else if(datafile=="data_9192"||datafile=="data_9192.rda")
{load("/Users/blahblahblah/data_9192.rda")
state.in=as.data.frame(data_9192[[which(names(data_9192)==(tolower(state)))]][1]
state.out=as.data.frame(data_9192[[which(names(data_9192)==(tolower(state)))]][2]}

I know it's not elegant or efficient or anything, and even though it works, I'd still like to have a much better way of doing this. Any ideas?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3084629
  • 445
  • 2
  • 4
  • 7
  • Since you are not asking a very specific question, you could start by searching SO for things like [r read file folder](http://stackoverflow.com/search?q=[r]+read+file+folder). There are many questions and answers on how to read files into R already. – talat May 22 '14 at 18:07

1 Answers1

0

The load() function returns the names of the objects that it "inflated" from the rda file. So you can do something like

datafile <- gsub("\\.rda$", "", datafile)
dats <- load(paste("/Users/blahblahblah/", datafile, ".rda", sep="")
stopifnot(length(dats)==1)
dd<-get(dats[1])
state.in  <-as.data.frame(dd[[which(names(dd)==(tolower(state)))]][1]
state.out <-as.data.frame(dd[[which(names(dd)==(tolower(state)))]][2]
MrFlick
  • 195,160
  • 17
  • 277
  • 295