不完全理解SE如何跨dplyr动词工作

不完全理解SE如何跨dplyr动词工作,r,dplyr,R,Dplyr,我试图了解SE如何在dplyr中工作,以便使用变量作为这些函数的输入。我在理解这在不同的函数中是如何工作的以及何时应该做什么方面遇到了一些困难。理解这背后的逻辑真的很好 以下是一些例子: library(dplyr) library(lazyeval) a <- c("x", "y", "z") b <- c(1,2,3) c <- c(7,8,9) df <- data.frame(a, b, c) 现在我想用同样的方法过滤。不知道为什么我的第一次尝试没有成功

我试图了解SE如何在
dplyr
中工作,以便使用变量作为这些函数的输入。我在理解这在不同的函数中是如何工作的以及何时应该做什么方面遇到了一些困难。理解这背后的逻辑真的很好

以下是一些例子:

library(dplyr)
library(lazyeval)


a <- c("x", "y", "z")
b <- c(1,2,3)
c <- c(7,8,9)

df <- data.frame(a, b, c)
现在我想用同样的方法过滤。不知道为什么我的第一次尝试没有成功

#Apply the same logic to filter_. the following doesn't return a result
val.to.filter <- "z"
filter_(df, "a" == val.to.filter)

#Do I need to use interp? Works. What's the difference compared to the above?
expr <- interp(~(a == val), val = val.to.filter)
filter_(df, expr)
现在我转到
重命名
。知道什么对
mutate
有效,知道我必须对
过滤器使用
interp
,我尝试了以下方法

#Now let's try to rename. Qouted constant, unqouted variable. Doesn't work
new.name <- "NEW"
rename_(df, "a" = new.name)

#Do I need an eval here? It worked for the filter so it's worth a try. Doesn't work 'Error: All arguments to rename must be named.'
expr <- interp(~(a == val), val = new.name)
rename_(df, expr) 
#现在让我们尝试重命名。Qouted常量,未Qouted变量。不起作用

new.name此处的差异与您使用的
dplyr
动词无关。它们与您尝试使用变量的位置有关。您正在混合变量是否用作函数参数,以及是否应将其解释为
名称
字符
字符串

情景1: 您希望将变量用作参数名称。例如在您的
mutate
示例中

mutate(df, new = b)
这里的
new
是函数参数的名称,它位于
=
的左侧。唯一的方法是使用
.dots
参数。像

col.name <- 'new'
mutate_(df, .dots = setNames(list(~b), col.name))
或者简单地说:

mutate_(df, new = b)
情景3 你想做一些可变和固定的组合。也就是说,表达式只能是部分变量。为此,我们使用
interp
。例如,如果我们想做一些事情,比如:

mutate(df, new = b + 1)
但是能够改变
b

v <- 'b'    
mutate_(df, new = interp(~var + 1, var = as.name(v)))

v我特别赞成只使用
get
和标准表单。如果我使用
get('a')==val.to.filter
我就得到了我想要的,而不必去乱搞我的过滤器的奇怪公式形式
mutate(df,col.name=“b”)
肯定不会像你说的那样做。NSE中引号的意义是什么?文档说明必须引用输入,但在最后一个示例中“new”似乎不是这样。我只是想弄明白为什么。谢谢
=
之后的所有内容都需要引用。您是否阅读了《小插曲》(“nse”)
mutate_(df, new = b)
mutate(df, new = b + 1)
v <- 'b'    
mutate_(df, new = interp(~var + 1, var = as.name(v)))