R-beta: Applying functions to vectors--question

Martyn Plummer plummer at iarc.fr
Mon Sep 14 09:41:12 CEST 1998


Marc Lipsitch wrote:

> I have constructed a function f (below) which tests if its argument is
> negative; if it is,
> it returns 0, if not, it returns sqrt(f).
> 
> This works fine with scalar arguments.
> 
> If you give it a vector argument, however, it seems to have trouble.

You want to use the "ifelse" function,  to apply a condition
element-wise
to a vector, e.g.

f <- function(e)
	ifelse(e>0,sqrt(e),0)

Or, to avoid the warning (which comes about because both alternative
answers
are evaluated before deciding which one to apply)

f <- function(e)
	sqrt(ifelse(e>0,e,0))

NB The help page for "if" points to the help page for "ifelse" which
gives
an example very similar to this.

Martyn
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list