Re: [R] How do you exit a function in R?

From: Roland Rau <roland.rproject_at_gmail.com>
Date: Thu, 29 May 2008 14:46:15 -0400

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



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 29 May 2008 - 19:22:24 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 29 May 2008 - 19:30:42 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive