在R:如何在不丢失初始函数名的情况下将函数名(不作为字符)作为参数传递给另一个内部函数?

时间:2018-06-05 02:27:30

标签: r dplyr quoting

我有两个功能:

  
      
  1. <p:dialog modal="true" widgetVar="successDialog" header="Info" closable="false" appendTo="@(body)"> <h:panelGrid columns="1" cellpadding="2"> <h:outputText value="Save data berhasil" /> <center> <p:commandButton value="Ok" action="/prpk_paperless/master_prpk.xhtml?faces-redirect=true" onclick="PF('successDialog').hide()" immediate="true"/> </center> </h:panelGrid> </p:dialog> <p:dialog modal="false" widgetVar="failedDialog" header="Info" closable="false"> <h:panelGrid columns="1" cellpadding="2"> <h:outputText value="Save data failed" /> <center> <p:commandButton value="Ok" action="#" onclick="PF('failedDialog').hide()" /> </center> </h:panelGrid> </p:dialog> 完成工作
  2.   
  3. Worker调用&#34;工人&#34;并要求它执行由 name
  4. 调用的给定函数   

如果我直接调用Boss,它会收到函数体及其名称,以便它可以同时使用它们。但是,如果我通过Worker调用Worker,则BossBoss中的函数名称屏蔽为FUN

Worker

我厌倦了与require(magrittr) require(dplyr) df <- data.frame(one = c(1,1,1), two = c(1,3,NA)) Worker <- function(df, feature, FUN, ...) { newvarname <- paste0(substitute(FUN), feature) df %>% mutate(!!newvarname := FUN(!!as.name(feature), ...)) } Boss <- function(df, feature, FUN, ...) { df %>% Worker(feature, FUN, ...) } Boss(df, "two", mean, na.rm = T) # one two FUNtwo # 1 1 1 2 # 2 1 3 2 # 3 1 NA 2 Worker(df, "one", mean) # one two meanone # 1 1 1 1 # 2 1 3 1 # 3 1 NA 1 一起玩,但没有任何帮助。这是否意味着,R不能将整个函数对象 - 名称和正文 - 作为参数传递?

2 个答案:

答案 0 :(得分:1)

您可以在eval(substitute())内添加Boss,但它看起来并不令人满意

Boss <- function(df, feature, FUN, ...) {
  eval(substitute(df %>% Worker(feature, FUN,...)))
}

Boss(df, "two", mean, na.rm = T)
  one two meantwo
1   1   1       2
2   1   3       2
3   1  NA       2

答案 1 :(得分:0)

以下是一种使用rlang来处理它的方法:

library(rlang)

df <- data.frame(one = c(1,1,1), two = c(1,3,NA))

Worker <- function(df, feature, FUN, ...) {

    if (!is_quosure(FUN)) {
        fun_q <- quo(FUN)
        newvarname <- paste0(substitute(FUN), feature)
    }
    else {
        fun_q <- FUN
        newvarname <- paste0(quo_text(fun_q), feature)
    }

    df %>% mutate(!!newvarname := eval(fun_q)(!!as.name(feature), ...))
}

Boss <- function(df, feature, FUN, ...) {
    fun_q <- enquo(FUN)
    df %>% Worker(feature, fun_q, ...)
}

Boss(df, "two", mean, na.rm = T)

  one two meantwo
1   1   1       2
2   1   3       2
3   1  NA       2

Worker(df, "one", mean)

  one two meanone
1   1   1       1
2   1   3       1
3   1  NA       1