简体   繁体   English

R中的链替代()

[英]chain substitute() in R

I am trying to get names in a list twice passed in function calls, such as : 我试图获取两次通过函数调用传递的列表中的名称,例如:

fn1 <- function(arg1){
    a<-substitute(arg1)
    print(a)
}
fn2 <- function(arg2){
    fn1(arg2[[2]])
}  
fn2(list(list(sum,sum,min),list(min,min,sum)))

And would like the print to display 并希望显示打印

list(min,min,sum)

I am trying combinations of eval() and substitute() but can't get it right. 我尝试的组合eval()substitute()但不能得到它的权利。

Perhaps this may help 也许这可能有所帮助

fn1 <- function(...) {
      lapply(substitute(...)[-1], deparse)
     }

fn2 <- function(...){
  fn1(...)[[2]]
}

fn2(list(list(sum,sum,min),list(min,min,sum)))
#[1] "list(min, min, sum)"

fn2 can remain same, use this as fn1 fn2可以保持不变,将其用作fn1

 fn1 <- function(arg1){
    print(deparse(arg1[[2]]))
 }

but call the function using quote() around the function names min,sum,etc 但是在函数名称min,sum等周围使用quote()调用函数

fn2(list(list(quote(sum),quote(sum),quote(min)),
       list(quote(min),quote(min),quote(sum))))

Output 产量

fn2(list(list(quote(sum),quote(sum),quote(min)),list(quote(min),quote(min),quote(sum))))
[1] "list(min, min, sum)"

An imperfect solution 不完善的解决方案

Seems like there are no fn1-change only answers. 似乎没有仅fn1更改答案。 This is what I prefer (smaller modifification to the fn2 call) but I don't accept it as it doesn't really allows to chain substitute calls: 这是我喜欢的(对fn2调用的修改较小),但我不接受它,因为它实际上不允许链接替代调用:

fn1 <- function(arg1){
    print(arg1)
}
fn2 <- function(arg2){
    fn1(arg2[[3]])
}
fn2(quote(c(list(sum,sum,min),list(min,min,sum))))

Explanation 说明

The key is to pass a quoted expression to fn2, this prevents evaluation of the string: 关键是将带引号的表达式传递给fn2,这样可以防止对字符串进行求值:

fn2(quote(list(list(sum,sum,min),list(min,min,sum))))

As the call is quoted, the first item is list , the second is list(sum,sum,min) , the third is ̀ list(min,min,sum) . 由于该呼叫被引用时,第一项是list ,该第二被list(sum,sum,min) ,第三个是list(min,min,sum) I then pass arg2[[3]] to fn1: 然后,我将arg2[[3]]传递给fn1:

fn2 <- function(arg2){
    fn1(arg2[[3]])
}

And printing is obvious in fn1: 在fn1中,打印很明显:

fn1 <- function(arg1){
    print(arg1)
}

An answer not implying a modification of the fn2 call , inspired by heavy reading of Hadley's course 答案并不暗示对fn2电话的修改,这得益于对哈德利课程深入研究

As substitute() can only be called one level up from the call, define two functions: 由于只能在调用的上一级调用substitute() ,因此请定义两个函数:

fn1_q <- function(arg1){
    print(arg1)
}
fn1 <- function(arg1){
    fn1_q(substitute(arg1))
}
fn2 <- function(arg2){
    exprArg2 <- substitute(arg2)
    fn1_q(exprArg2[[3]])
}
> fn2(list(list(sum,sum,min),list(min,min,sum)))
list(min, min, sum)
> 
> fn1(list(min,min,sum))
list(min, min, sum)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM