循环分配和删除对象:eval(parse(paste( [英] Assigning and removing objects in a loop: eval(parse(paste(

查看:107
本文介绍了循环分配和删除对象:eval(parse(paste(的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个循环分配对象的方法.我已经读到某种形式的eval(parse(是执行此操作所需要的,但是我遇到了列出invalid textno such file or directory.的错误,以下是我通常尝试做的示例代码:

I am looking to assign objects in a loop. I've read that some form of eval(parse( is what I need to perform this, but I'm running into errors listing invalid text or no such file or directory. Below is sample code of generally what I'm attempting to do:

x <- array(seq(1,18,by=1),dim=c(3,2,3))
for (i in 1:length(x[1,1,])) {
  eval(parse(paste(letters[i],"<-mean(x[,,",i,"])",sep="")
}

当我使用完这些对象后,我想删除它们(实际的对象非常大,以后会导致内存问题...)

And when I'm finished using these objects, I would like to remove them (the actual objects are very large and cause memory problems later on...)

for (i in 1:length(x[1,1,])) eval(parse(paste("rm(",letters[i],")",sep="")))

此脚本的eval(parse(paste(部分均返回invalid textno such file or directory的错误.我在使用eval(parse(时会缺少什么吗?有没有更简单/更好的方法来循环分配对象?

Both eval(parse(paste( portions of this script return errors for invalid text or no such file or directory. Am I missing something in using eval(parse(? Is there a easier/better way to assign objects in a loop?

推荐答案

这是一种令人作呕且令人沮丧的方法.使用assign进行分配,使用rm的list参数删除对象.

That's a pretty disgusting and frustrating way to go about it. Use assign to assign and rm's list argument to remove objects.

> for (i in 1:length(x[1,1,])) {
+   assign(letters[i],mean(x[,,i]))
+ }
> ls()
[1] "a" "b" "c" "i" "x"
> a
[1] 3.5
> b
[1] 9.5
> c
[1] 15.5
> for (i in 1:length(x[1,1,])) {
+   rm(list=letters[i])
+ }
> ls()
[1] "i" "x"
> 

每当您需要使用parse时,请记住财富(106):

Whenever you feel the need to use parse, remember fortune(106):

如果答案是parse(),则应该 通常会重新考虑问题.
-Thomas Lumley,R-help(2005年2月)

If the answer is parse() you should usually rethink the question.
-- Thomas Lumley, R-help (February 2005)

这篇关于循环分配和删除对象:eval(parse(paste(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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