在`$`登录R后使用替代项 [英] Working with substitute after `$` sign in R
问题描述
我想知道下面的代码中的 G
是否可以像 D $ post == 1
之后在 $
之后工作有效吗?
I was wondering if there is a way that G
in my code below could work after $
just like D$post == 1
works?
D <- data.frame(post = 1:10, out = 2:11)
G <- substitute(post == 1)
D$G ## can we make `G` to work like `D$post`?
D$post == 1 ## Works
推荐答案
您可以执行以下操作:
G <- substitute(post == 1)
E <- substitute(D$G, list(G = G))
#D$post == 1
该表情看起来像您想要的,对吗?嗯,事实并非如此,您可以在尝试对其进行评估时看到:
That expression looks like what you want, right? Well, it isn't, as you can see when you try to evaluate it:
eval(E)
#Error in D$post == 1 : invalid subscript type 'language'
让我们更详细地检查该表达式:
Let's inspect the expression in more detail:
as.list(E)
#[[1]]
#`$`
#
#[[2]]
#D
#
#[[3]]
#post == 1
好的,我们有一个函数调用(对 $
),带有两个参数( D
和 post == 1
).第二个参数是一个表达式,而 $
需要一个名称.
OK, we have one function call (to $
) with two arguments (D
and post == 1
). The second argument is an expression whereas $
expects a name.
让我们将其与它的外观进行比较:
Let's compare this with how it should look like:
as.list(quote(D$post == 1))
#[[1]]
#`==`
#
#[[2]]
#D$post
#
#[[3]]
#[1] 1
as.list(quote(D$post == 1)[[2]])
#[[1]]
#`$`
#
#[[2]]
#D
#
#[[3]]
#post
因此, D $ post == 1
实际上是对两个嵌套函数的调用,并且将其解析为:
So, D$post == 1
is actually a call to two nested functions and get's parsed to this:
`==`(`$`(D, post), 1)
我希望这可以弄清楚为什么"[w]在$符号后进行替换"并不是那么简单.
I hope this clarifies why "[w]orking with substitute after $ sign" is not so simple.
如果您了解如何解析表达式,仅说明这仍然可行:
Just to show that is still possible, if you understand how the expression is parsed:
E <- quote(D$x)
E[[3]] <- G[[2]]
G[[2]] <- E
eval(G)
#[1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
但是,这样的代码确实很难维护和调试.不要这样
However, such code is really hard to maintain and debug. Don't do this.
如@joran所示,您可以使用像 with
这样的函数来对data.frame中的表达式 post == 1
求值,该函数基本上只是 eval(G,D,parent.frame())
.但是,这是一条危险且湿滑的道路,可能会导致巨龙.让我在 help("subset")
此处引用相关警告:
As @joran shows, you can use functions like with
that evaluate the expression post == 1
within the data.frame, which is basically just a wrapper for eval(G, D, parent.frame())
. However, that's a dangerous and slippery path that can lead to dragons. Let me quote the relevant warning from help("subset")
here:
这是旨在交互使用的便捷功能.为了编程时,最好使用标准的子集功能,例如[,尤其是参数子集的非标准评估可能会带来意想不到的后果.
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.
这篇关于在`$`登录R后使用替代项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!