dplyr的功能与非标准评价
我刚读完,开始掌握函数的非标准评估。这篇文章的具体问题是,如何使用tidyverse(例如dplyr的功能与非标准评价,r,function,dplyr,R,Function,Dplyr,我刚读完,开始掌握函数的非标准评估。这篇文章的具体问题是,如何使用tidyverse(例如quo(),!!,等等)直接编写下面的代码“而不是base-R方法eval(),替换,等等 library(tidyverse) xy <- data.frame(xvar = 1:10, yvar = 11:20) plotfunc <- function(data, x, y){ y.sqr <- (eval(substitute(y), envir = data))^2 p
quo()
,!!
,等等)直接编写下面的代码“而不是base-R方法eval()
,替换,等等
library(tidyverse)
xy <- data.frame(xvar = 1:10, yvar = 11:20)
plotfunc <- function(data, x, y){
y.sqr <- (eval(substitute(y), envir = data))^2
print(
ggplot(data, aes_q(x = substitute(x), y = substitute(y.sqr))) +
geom_line()
)
}
plotfunc(xy, xvar, yvar)
库(tidyverse)
xy您可以执行以下操作:
library(tidyverse)
xy <- data.frame(xvar = 1:10, yvar = 11:20)
plotfunc <- function(data, x, y){
x <- enquo(x)
y <- enquo(y)
print(
ggplot(data, aes(x = !!x, y = (!!y)^2)) +
geom_line()
)
}
plotfunc(xy, xvar, yvar)
库(tidyverse)
xy使用rlang_0.4.0
,我们可以使用整洁的求值运算符({…}
)或卷曲
,它将引号和unquote抽象为一个插值步骤。这使得创建函数更容易
library(rlang)
library(ggplot2)
plotfunc <- function(data, x, y){
print(
ggplot(data, aes(x = {{x}}, y = {{y}}^2)) +
geom_line()
)
}
plotfunc(xy, xvar, yvar)
库(rlang)
图书馆(GG2)
plotfunc
library(rlang)
library(ggplot2)
plotfunc <- function(data, x, y){
print(
ggplot(data, aes(x = {{x}}, y = {{y}}^2)) +
geom_line()
)
}
plotfunc(xy, xvar, yvar)