简体   繁体   English

如何调用具有同名字符变量的对象

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

I'm trying to write a function in R to batch-analyse a number of files in a similar manner.我正在尝试在 R 中编写一个函数来以类似的方式批量分析多个文件。 The files are of class ExpressionSetIllumina .这些文件属于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:我现在想要做的是使用i (字符串"SSD.BA.vsn" )将对象SSD.BA.vsn分配给新的对象数据,以便:

>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.但是到目前为止,无论我尝试过什么,都只是将数据作为与 i 具有相同值的字符向量返回,或者根本不起作用。 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?如何使用字符串对象名称对对象执行某些操作?

I think you want get .我想你想要get

data <- get(i)

That said, once you start using get (and its counterpart, assign ), you usually end up with horrible unreadable code.也就是说,一旦你开始使用get (及其对应物, assign ),你通常会得到可怕的不可读代码。

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 .对于像您这样的批量分析,通常最好将所有数据读入数据框列表,然后自由使用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. mget是一次检索多个变量的get版本。 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.现在您有一个列表列表:顶级列表与文件相关,低级列表包含从该文件加载的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM