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

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

问题描述

我正在尝试在 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.

对于像您这样的批量分析,通常最好将所有数据读入数据框列表,然后自由使用 lapply.类似的东西:

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 是一次检索多个变量的 get 版本.这里用来检索所有调用load加载的东西.

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天全站免登陆