[R] apply( )

Chuck Cleland ccleland at optonline.net
Thu May 10 17:44:30 CEST 2007


Greg Tarpinian wrote:
> I have a question that must have a simple answer (but eludes me).
> I need a row-by-row logical comparison across three numeric variables
> in
> a data frame: foo$x, foo$y, foo$z.  The logic is
> 
>    if( x < y || x > z ) 1 else 0
> 
> for a particular row.
> 
> It is simple and very inefficient to use for(i in 1:length(foo$x)){ }
> loops.  How can I accomplish this using sappy( ) / lapply( ) / apply( )
> or some other more efficient method?

X <- as.data.frame(matrix(rnorm(30), ncol=3))
X
            V1         V2         V3
1  -0.48026236  0.8629789 -1.2600858
2  -1.32408219 -0.5590268  1.1310638
3   0.02717575 -0.5661402  0.7824019
4   0.80783373  0.2300440 -0.4477275
5   1.24518907 -0.3778392  1.7546530
6  -0.39254125 -1.0388962 -0.4436296
7  -1.44473455  1.8606963  0.4253889
8  -0.63543047 -1.6408418 -1.0409473
9   0.81075970  0.3914066 -1.0361739
10  1.66021280 -1.6694101 -0.4810839

with(X, ifelse(V1 < V2 | V1 > V3, 1, 0))
 [1] 1 1 0 1 0 1 1 1 1 1

> Thank you in advance,
> 
>     Greg
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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. 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list