[R] Creat new column based on condition

Frank E Harrell Jr f.harrell at vanderbilt.edu
Fri Apr 21 23:45:12 CEST 2006


Duncan Murdoch wrote:
> On 4/21/2006 4:05 PM, Sachin J wrote:
> 
>>Hi,
>>   
>>  How can I accomplish this task in R?
>>   
>>    V1
>>    10
>>    20
>>    30
>>    10
>>    10
>>    20
>>     
>>  Create a new column V2 such that: 
>>  If V1 = 10 then V2 = 4
>>  If V1 = 20 then V2 = 6
>>  V1 =   30 then V2 = 10
> 
> 
> Gabor's solution is fine; something that looks a little bit more like 
> your code is this:
> 
>   V2 <- NA
>   V2 <- ifelse( V1 == 10, 4, V2)
>   V2 <- ifelse( V1 == 20, 6, V2)
>   V2 <- ifelse( V1 == 30, 10, V2)

or

V2 <- 4*(V1==10)+6*(V2==20)+10*(V2==30)
V2[V2==0] <- NA

Frank

> 
> or
> 
>   V2 <- ifelse( V1 == 10, 4,
>           ifelse( V1 == 20, 6,
>             ifelse( V1 == 30, 10, NA )))
> 
> (where the NA is to handle any unexpected case where V1 isn't 10, 20 or 
> 30).  My preference would be to use just one assignment, and if I was 
> sure 10, 20 and 30 were the only possibilities, would use
> 
>   V2 <- ifelse( V1 == 10, 4,
>           ifelse( V1 == 20, 6, 10 ))
> 
> Duncan Murdoch
> 
>>   
>>  So the O/P looks like this
>>   
>>    V1  V2
>>    10   4
>>    20   6
>>    30  10
>>    10   4
>>    10   4  
>>    20   6
>>   
>>  Thanks in advance.
>>   
>>  Sachin

-- 
Frank E Harrell Jr   Professor and Chair           School of Medicine
                      Department of Biostatistics   Vanderbilt University




More information about the R-help mailing list