这是一个带注释的版本。它正在创建接受值a并b计算的函数c。它首先测试值是否为数字,如果它们不是数字,它将打印您的错误消息,否则它将忽略那些大括号内的内容并继续下一个测试。第二个测试是检查两者是否都大于零(看到三角形不能有长度为零或负长度的边)。如果它满足两个都 > 0 的条件,那么它将计算c,如果不是,它将给出错误说明存在负值。
# Feed it the values a and b (length of the two sides)
pythag <- function(a,b){
# Test that both are numeric - return error if either is not numeric
if(is.numeric(a) == FALSE | is.numeric(b) == FALSE){
return('I need numeric values to make this work')}
# Test that both are positive - return length of hypoteneuese if true...
if(a > 0 & b > 0){
return(sqrt((a^2)+(b^2)))
}else{
# ... give an error either is not positive
return('Values Need to be Positive')
}
}
这是一个更精简的版本:
pythag <- function(a,b){
if(is.numeric(a) == FALSE | is.numeric(b) == FALSE){return('I need numeric values to make this work')}
if(a > 0 & b > 0){return(sqrt((a^2)+(b^2)))}
else{return('Values Need to be Positive')}
}
这就是您的示例返回的内容:
> pythag(4,5)
[1] 6.403124
> pythag("A","B")
[1] "I need numeric values to make this work"
> pythag(-4,-5)
[1] "Values Need to be Positive"