【问题标题】:How to check if a variable is passed to a function with or without quotes?如何检查变量是否传递给带引号或不带引号的函数?
【发布时间】:2019-05-13 15:00:13
【问题描述】:

我正在尝试编写一个 R 函数,该函数可以将带引号或不带引号的数据框变量名或变量名向量作为参数。问题是当用户插入未加引号的数据框列名作为函数输入参数时,它会导致“找不到对象”错误。如何检查变量名是否被引用?

我已经尝试过 exists()、missing()、substitute(),但它们都不适用于所有组合。


# considering this printfun as something I can't change 
#made it just for demosnstration purposeses
printfun <- function(df, ...){
  for(item in list(...)){
    print(df[item])
  }

}
myfun<-function(df,x){

  #should check if input is quoted or unquoted here 

  # substitute works for some cases not all (see below)
  new_args<-c(substitute(df),substitute(x))
  do.call(printfun,new_args)

}
#sample data
df<-data.frame(abc=1,dfg=2)

#these are working
myfun(df,c("abc")) 
myfun(df,c("abc","dfg"))
myfun(df,"abc")

#these are failing with object not found
myfun(df,abc)
myfun(df,c(abc))

我可以用 try Catch 块区分 myfun(df,abc)myfun(df,"abc")。虽然这看起来不是很整洁。

但我还没有找到任何方法来区分 myfun(df,c(abc)) 中的第二个参数和 myfun(df,abc)

或者,我可以以某种方式检查错误是否来自缺少引号,因为我猜 object not found 错误也可能是由其他内容(例如数据框名称)输入错误引起的?

【问题讨论】:

    标签: r function dataframe


    【解决方案1】:

    这似乎适用于您的所有情况:

    myfun<-function(df,x){
    
      sx <- substitute(x)
      a <- tryCatch(is.character(x), error = function(e) FALSE)
      if (a) {
          new_x <- x
      } else {
          cx <- as.character(sx)
          if (is.name(sx)) {
              new_x <- cx
          } else if (is.call(sx) && cx[1] == "c") {
              new_x <- cx[-1]
          } else {
              stop("Invalid x")
          }
      }
      new_args <- c(substitute(df), as.list(new_x))
      do.call(printfun, new_args)
    }
    

    但是,我觉得你正在尝试做的事情有些奇怪。

    【讨论】:

    • 谢谢!检查is.call 是否是我所缺少的!为什么你觉得很奇怪?我对 R 不是很熟悉,但根据我的经验,用户在需要输入带引号的列名和未加引号的列名到函数时会感到很困惑。例如,ggplot2 中的 aes 只需要不带引号,而 aes_string 用于引用的数据名列名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多