gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:26:25 27 4
gpt4 key购买 nike

我正在尝试编写一个 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 block 区分 myfun(df,abc)myfun(df,"abc")。虽然这看起来不是很整洁。

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

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

最佳答案

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

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

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

关于r - 如何检查变量是否传递给带引号或不带引号的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56115020/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com