我有功能,如果参数是唯一的,希望抛出错误
到目前为止,我试过了:
PrintLetters <- function(name, name2, name3){
if (!unique(args)){
stop("Enter 1 to 3 unique arguments")
}
print(paste(name,name2,name3,sep=" "))
}
PrintLetters("a","b","c")
错误结果
Error in unique.default(args) : unique() applies only to vectors
尝试将args保存到向量
PrintLetters <- function(name, name2, name3){
v_args <- c(args)
if (!unique(v_args)){
stop("Enter 1 to 3 unique arguments")
}
print(paste(name,name2,name3,sep=" "))
}
PrintLetters("a","b","c")
新错误
Error in !unique(v_args) : invalid argument type
请指导
答案 0 :(得分:1)
你可以试试这个:
PrintLetters <- function(name, name2 = NULL, name3=NULL){
args <- unlist(mget(names(formals())))
if ( anyDuplicated(args) ){
stop("Enter 1 to 3 unique arguments")
}
print(paste(name,name2,name3,sep=" "))
}
PrintLetters("a","b","c")
# [1] "a b c"
PrintLetters("a","b","a")
# Error in PrintLetters("a", "b", "a") : Enter 1 to 3 unique arguments