fxz <- function (x,d=2)
{
if(d !=2) d = d
which(x %% d ==0)
}
> fxz(x=2:12,d=13)
integer(0)
我在which语句中使用了modulo运算符来返回除数的0余数的所有数字位置。由于它返回integer(0)
,我怎么能让它返回null呢?
另一个想法。当d不是单个数值时,我希望函数停止并输出警告消息。 我一直在尝试像#34;如果d不等于数字,请停止(&#34;消息&#34;)&#34;。
感谢您的帮助。我对R编程很陌生
答案 0 :(得分:0)
这是你的函数,检查d的类和结尾的结果长度:
fxz <- function (x, d=2) {
# Check d is an integer or numeric
if (!(is.integer(d) | is.numeric(d))) {
stop("The d argument must be numeric")
}
result = which(x %% d ==0)
# If result has length 0 return NULL instead of result
if (length(result) == 0) {
return(NULL)
} else {
return(result)
}
}
示例输出:
> fxz(x=2:12, d=2)
[1] 1 3 5 7 9 11
> fxz(x=2:12, d=13)
NULL
> fxz(x=2:12, d="hey")
Error in fxz(x = 2:12, d = "hey") : The d argument must be numeric
答案 1 :(得分:0)
当x不是单个数值
时,此函数停止并输出警告消息fxz <- function (x) {
# Check d is an integer or numeric and length == 1
stopifnot( is.numeric(x), (length(x) == 1) )
}