R / nse / 将变量双重移交给子函数

R / nse / Double-handover of a variable to a sub-function

我有两个函数要用一个包装函数包装在一起以提高可用性。包装函数包含一个变量(数据框中的列名),该变量应从包装函数移交给其中一个子函数。

强烈减少的例子:

子功能 1:创建数据

datafun <- function() {

    df_data <- data.frame(x = rep(1:20, 3), 
                          y = rnorm(60),
                          ga = sample(c("a", "b"), 30, replace = TRUE),
                          gb = sample(c("x", "y"), 20, replace = TRUE))

    df_data
}

子功能 2:绘图

plotfun <- function(df, gvar) {

    gvar_q = deparse(substitute(gvar))

    g <- ggplot2::ggplot(df, ggplot2::aes_string(x = "x", y = "y", color = gvar_q)) +
        ggplot2::geom_line() +
        directlabels::geom_dl(ggplot2::aes(label = {{gvar}}), method = list("last.points"))

    g
}

环绕函数

wrapfun <- function(gvar) {

    dat <- datafun()
    plot <- plotfun(df = dat, gvar = {{gvar}})

    plot
}

测试

直接使用这两个子函数没有问题:

#works
d <- datafun()
plotfun(d, gvar = ga)

但是使用包装函数会导致错误

# doesn't work
wrapfun(gvar = ga)
>Error in FUN(X[[i]], ...) : object 'ga' not found

请注意(据我所知),directlabels::geom_dl 不接受 aes_string 作为解决方法。所以看来我不能将 gvar 作为字符串传递给函数。

ggplot 的最新版本中,您不使用 deparse/substituteaes_string。您专门使用新的准注解语法。对于这个例子,你应该做

plotfun <- function(df, gvar) {

   ggplot2::ggplot(df, ggplot2::aes(x = x, y = y, color = {{gvar}})) +
     ggplot2::geom_line() +
     directlabels::geom_dl(ggplot2::aes(label = {{gvar}}), method = list("last.points"))

}

那么您的函数将直接和在 wrapfun()

内运行