Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an object with the character variable of the same name

Tags:

r

r-faq

I'm trying to write a function in R to batch-analyse a number of files in a similar manner. The files are of class ExpressionSetIllumina. I can make a character (string) vector with names of all files in the directory and load each of them:

list = list.files() for (i in list[1]) {       load(i) } 

This loads files correctly

> ls() [1] "i"                    "list"                 "SSD.BA.vsn" > class(SSD.BA.vsn) [1] "ExpressionSetIllumina" attr(,"package") [1] "beadarray" 

What I want to do now is to use i (character string "SSD.BA.vsn") to assign object SSD.BA.vsn to a new object data so that:

>data = SomeFunction(i) >class(data) [1] "ExpressionSetIllumina" attr(,"package") [1] "beadarray" 

But whatever I've tried so far just returns data as a character vector of the same value as i or doesn't work at all. So I wonder if there's a function that would do it for me or whether I need to go about it some other way.

I have the name of an object or variable stored as a string in a character vector. How can I use the string object name to do something to the object?

like image 988
Ophiothrix Avatar asked Jan 31 '12 17:01

Ophiothrix


People also ask

How do I assign an object to a name in R?

names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named.


1 Answers

I think you want get.

data <- get(i) 

That said, once you start using get (and its counterpart, assign), you usually end up with horrible unreadable code.

For batch analyses like yours, it is often better to read all your data into a list of data frames, then make liberal use of lapply. Something like:

data_files <- list.files() all_vars <- lapply(data_files, function(file) {   vars_loaded <- load(file)   mget(vars_loaded, parent.frame()) }) 

mget is the version of get that retrieves multiple variables at once. Here it is used to retrieve all the things that were loaded by the call to load.

Now you have a list of lists: the top level list is related to the file, lower level lists contain the variables loaded from that file.

like image 86
Richie Cotton Avatar answered Oct 14 '22 15:10

Richie Cotton