如何检查是否将变量传递给带有或不带有引号的函数?

时间:2019-05-13 15:00:13

标签: r function dataframe

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

我已经尝试过exist(),missing(),alternate(),但是它们都不适合所有组合。


# 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)

或者,我能以某种方式检查错误是否是由于缺少引号引起的,因为我猜找不到对象的错误也可能是由于其他类型(例如数据框名称)输入错误而引起的?

1 个答案:

答案 0 :(得分:0)

这似乎适用于所有情况:

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)
}

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

相关问题