[R] vectorizing a function

Greg Snow Greg.Snow at imail.org
Tue Jul 7 21:51:55 CEST 2009


For this case it is quite simple, see ?ifelse

> z <- ifelse( x > 0, y, -y )

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Steve Jaffe
> Sent: Tuesday, July 07, 2009 1:42 PM
> To: r-help at r-project.org
> Subject: [R] vectorizing a function
> 
> 
> I'm sure I'm missing something obvious but I'm not seeing how to simply
> "vectorize" a function of two or more variables.
> 
> Say I have
> f <- function(x,y) if (x>0) y else -y
> 
> Now I have vectors x and y of equal length and I'd like to apply f
> element-wise. I.e. conceptually
>  z <- f(x,y) where x, y, z are vectors of the same length
> 
> Some magic involving apply?
> 
> Thanks
> --
> View this message in context: http://www.nabble.com/vectorizing-a-
> function-tp24380064p24380064.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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.




More information about the R-help mailing list