【发布时间】: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 错误也可能是由其他内容(例如数据框名称)输入错误引起的?
【问题讨论】: