如何即时命名变量?
是否可以动态创建新的变量名称?
我想将列表中的数据帧读取到末尾带有数字的新变量中。像 orca1、orca2、orca3 这样的东西...
如果我尝试类似的东西,
paste("orca",i,sep="")=list_name[[i]]
我会收到此错误
target of assignment expands to non-language object
有其他方法可以解决此问题吗?
Is it possible to create new variable names on the fly?
I'd like to read data frames from a list into new variables with numbers at the end. Something like orca1, orca2, orca3...
If I try something like
paste("orca",i,sep="")=list_name[[i]]
I get this error
target of assignment expands to non-language object
Is there another way around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在我看来,使用列表可能比使用
orca1
、orca2
等更好……那么它就是orca[1]
,orca[2]
, ...通常,您会创建一个仅用数字来区分的变量列表,因为该数字将是以后访问它们的便捷方法。
否则,
分配
正是您想要的。It seems to me that you might be better off with a list rather than using
orca1
,orca2
, etc, ... then it would beorca[1]
,orca[2]
, ...Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.
Otherwise,
assign
is just what you want.不要制作数据框。保留该列表,为其元素命名,但不要附加它。
这样做的最大原因是,如果您在旅途中创建变量,几乎总是稍后必须迭代它们中的每一个来执行一些有用的操作。在那里,您将再次被迫遍历您即时创建的每个名称。
命名列表的元素并遍历名称要容易得多。
就 Attach 而言,它在 R 中的编程实践非常糟糕,如果不小心的话可能会导致很多麻烦。
Don't make data frames. Keep the list, name its elements but do not attach it.
The biggest reason for this is that if you make variables on the go, almost always you will later on have to iterate through each one of them to perform something useful. There you will again be forced to iterate through each one of the names that you have created on the fly.
It is far easier to name the elements of the list and iterate through the names.
As far as attach is concerned, its really bad programming practice in R and can lead to a lot of trouble if you are not careful.
常见问题解答说:
如果你有,
你可以做
for
或
for
所以看起来当你想要计算使用变量(例如连接)的公式时你使用 GET,当你想要分配一个变量时你使用 ASSIGN预先声明的变量的值。
赋值语法:
分配(x,值)
x:变量名称,以字符串形式给出。不进行强制转换,并且将使用长度大于 1 的字符向量的第一个元素,并发出警告。
值:分配给 x 的值。
FAQ says:
If you have
you can do
for
or
for
So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.
Syntax for assign:
assign(x, value)
x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.
value: value to be assigned to x.
另一个棘手的解决方案是命名列表元素并附加它:
Another tricky solution is to name elements of list and
attach
it:还有这个选项?
它工作完美。在您放置的示例中,第一行丢失,然后给出错误消息。
And this option?
It works perfectly. In the example you put, first line is missing, and then gives you the error message.
使用
分配
:Use
assign
: