如何使用 allocate 来更改 R 数据框中的变量?
我尝试做这样的事情:
x <- data.frame(1:20)
attach(x)
assign("x2",1:20,pos="x")
但是,x$x2
给了我NULL
。
使用 x2 我得到了我想要的,但它不是 data.frame 的一部分。
在这种简单的情况下手动将 x2
附加到 x
可以工作,但在我需要的更复杂的情况下则不行。我尝试在循环中分配分配
,在该循环中循环分配
调用中使用的变量名。
I tried to do something like this:
x <- data.frame(1:20)
attach(x)
assign("x2",1:20,pos="x")
However, x$x2
gives me NULL
.
With x2
I get what I want but it is not part of the data.frame.
Attaching x2
to x
manually would work in this simple case but not in the more complex one I need. I try to assign
in a loop where I loop over the varnames used in the assign
call.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用内部:
不过使用
$
和[[
更干净,这也使列排序正确:Try using within:
It is cleaner to use
$
and[[
though, which also gets the column ordering right:?assign
的详细信息部分告诉您代码的行为方式为何。为什么不做一些简单的事情,比如:
The Details section of
?assign
tells you why your code behaves the way it does.Why not something simple like:
分配变量等的方法有很多,哪种方法最好取决于个人喜好。然而,有几点:
您不想
attach()
任何东西。十有八九它都会工作得很好,然后在你意想不到的时候咬你屁股,因为你所做的就是将你的对象的副本放在搜索路径上。修改原始对象,搜索路径上的对象不会更改以匹配。我个人不喜欢在一般使用中使用
$
访问内容。它很丑陋,并且会导致用户倾向于钻研物体并随心所欲地撕掉东西。对于你的数据来说并不重要,但是当我看到人们在做model$residuals
时我很担心。有更好的方法(在本例中为resid()
)。一些用户还用$
来猜测他们的模型公式。如果您正在编写数据分析脚本,并且可能会在几个月或几年后回来,那么在我看来,任何可以帮助您理解代码正在做什么的东西都是无价的。我发现
with()
和within()
对于您遇到的这类问题很有用,因为它们明确说明了您想要做什么。这更清楚:
比
即使他们做同样的事情。
within()
调用中的assign()
只是浪费打字,不是吗?There are lots of ways to assign a variable etc, and which is best will depend on personal taste. However, a couple of points:
You don't want to be
attach()
ing anything. It will work fine 9 times out of 10 and then bite you in the ass when you don't expect it, because all you are doing is placing a copy of your object on the search path. Modify the original object and the one on the search path doesn't change to match.I personally don't like accessing things with
$
in general use. It is ugly and engenders a tendency for users to just delve into objects and rip things out as they wish. Doesn't matter so much for your data, but when I see people doingmodel$residuals
I get worried. There are better ways (in this caseresid()
). Some users also riddle their model formulas with$
.If you are writing scripts for a data analysis that you might come back to months or years later, anything that can help you understand what your code is doing is an invalable bonus in my opinion. I find
with()
andwithin()
useful for the sort of problem you had because they are explicit about what you want to do.This is clearer:
than
Even though they do the same thing.
assign()
inside awithin()
call is just a waste of typing, is it not?