[R] How do you exit a function in R?
Roland Rau
roland.rproject at gmail.com
Thu May 29 20:46:15 CEST 2008
Hi
Bill Cunliffe wrote:
> For example, based on a certain condition, I may want to exit my code early:
>
>
>
> # Are there the same number of assets in "prices" and
> "positions"?
>
> if (nAssetPositions != nAssetPrices) {
>
> cat("Different number of assets! \n\n")
>
> <exit function>
>
> }
I think the easiest thing to use is the 'stopifnot()' function.
afunction <- function(myinput) {
stopifnot(is.numeric(myinput))
return(myinput * 2)
}
Alternatively, you can also do:
afunction2 <- function(myinput) {
if (!is.numeric(myinput)) stop("Input not numeric")
return(myinput * 2)
}
> afunction("roland")
Error: is.numeric(myinput) is not TRUE
> afunction2("roland")
Error in afunction2("roland") : Input not numeric
> afunction2(123)
[1] 246
> afunction(123)
[1] 246
>
I hope this helps,
Roland
More information about the R-help
mailing list