获取作为函数参数传递的变量的名称

时间:2020-10-29 19:04:54

标签: r

我试图捕获传递给函数的变量的名称,正确的方法。感兴趣的名称noi是数据框列或向量。以下是我的最低工作示例。理想情况下,我希望接收一个仅包含"noi"

的字符向量
library(dplyr)
df <- data.frame(noi = seq(1:3))

example_fun <- function( x ){
  deparse(substitute(x))  
}

结果取决于我构造输入的方式。现在我已经知道了为什么会发生这种情况,但是无论我如何调用该函数,我如何正确地做到这一点才能获得理想的结果。

# Base
example_fun(df$noi)
[1] "df$noi"

# Pipe
df$noi %>% example_fun() 
[1] "."

# Mutate
df %>% mutate(example_fun(noi))
  noi example_fun(noi)
1   1              noi
2   2              noi
3   3              noi

谢谢!

1 个答案:

答案 0 :(得分:2)

也许在另一个函数中用“ comment”属性修饰该变量?注意,要修饰的变量必须直接包装在修饰函数z中;否则,将引发错误(通过设计并出于鲁棒性考虑)。

example_fun <- function(x){
  attr(x, "comment")
}

z <- function(x) {
  nm <- substitute(x)
  nm <- as.character(
    if (is.symbol(nm) && !identical(nm, quote(.))) {
      nm
    } else if (length(nm) > 1L && (identical(nm[[1L]], quote(`[[`)) || identical(nm[[1L]], quote(`$`)))) {
      tail(nm, 1L)
    } else {
      stop("not a valid symbol or extract operator.", call. = match.call())
    }
  )
  `comment<-`(x, nm)
}

输出

> example_fun(z(df$noi))
[1] "noi"
> z(df$noi) %>% (function(x) x + 1) %>% example_fun()
[1] "noi"
> df %>% mutate(example_fun(z(noi)))
  noi example_fun(z(noi))
1   1                 noi
2   2                 noi
3   3                 noi
> z(df[["noi"]]) %>% example_fun()
[1] "noi"
> with(df, z(noi)) %>% example_fun()
[1] "noi"
> z(with(df, noi)) %>% example_fun()
 Error in z(with(df, noi)) : not a valid symbol or extract operator.
> df$noi %>% z()
 Error in z(.) : not a valid symbol or extract operator. 

...但是这可能不是一个可靠的方法。要以健壮的方式实现所需的目标非常困难,尤其是在涉及管道时。我认为您应该阅读Hadley的Advanced R,并了解有关绑定和环境如何工作的更多信息。

相关问题