[R] conditional replacement

Marc Schwartz (via MN) mschwartz at mn.rr.com
Tue May 23 20:49:46 CEST 2006


On Tue, 2006-05-23 at 11:40 -0700, Sachin J wrote:
> Hi 
>    
>   How can do this in R.
>    
>   >df 
>    
>   48        
>   1          
>   35        
>   32        
>   80
>    
>   If df < 30  then replace it with 30 and else if df > 60 replace it
> with 60. I have a large dataset so I cant afford to identify indexes
> and then replace. 
>   Desired o/p:
>    
>   48
>   30
>   35
>   32
>   60
>    
>   Thanx in advance.
>    
> Sachin

One approach is to combine the use of two ifelse() statements:

> ifelse(df < 30, 30, ifelse(df > 60, 60, df))
[1] 48 30 35 32 60

Recall that if the condition (1st argument) is TRUE, then the second
argument is evaluated and returned.  

If the condition is FALSE, then the third argument is evaluated, which
in this case is another ifelse().  The same logic follows within that
function.

See ?ifelse

HTH,

Marc Schwartz



More information about the R-help mailing list