如何使用具有相同名称的字符变量调用对象 [英] How to call an object with the character variable of the same name

查看:131
本文介绍了如何使用具有相同名称的字符变量调用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在R中编写一个函数,以类似的方式批量分析多个文件.这些文件属于ExpressionSetIllumina类.我可以使用目录中所有文件的名称制作一个字符(字符串)向量,并加载每个文件:

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)
}

这可以正确加载文件

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

我现在要做的是使用i(字符字符串"SSD.BA.vsn")将对象SSD.BA.vsn分配给新的对象数据,以便:

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"

但是到目前为止,我所做的任何尝试都只是将数据作为字符向量返回与i相同的值,或者根本不起作用.因此,我想知道是否有一个函数可以为我完成任务,还是我需要以其他方式解决问题.

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?

推荐答案

我认为您想要

I think you want get.

data <- get(i)

也就是说,一旦您开始使用get(及其对应版本 assign ),通常您会得到可怕的无法读取的代码.

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())
})

mgetget的版本,可一次检索多个变量.在这里,它用于检索调用调用所加载的所有内容.

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.

这篇关于如何使用具有相同名称的字符变量调用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆