[R] Assign value to new variable based on conditions on other variables

David Winsemius dwinsemius at comcast.net
Tue Apr 10 15:44:59 CEST 2012


On Apr 10, 2012, at 8:59 AM, David Winsemius wrote:

>
> On Apr 10, 2012, at 3:16 AM, aajit75 wrote:
>
>> I have got solution using within function as below
>>
>> dd$Seg <- 1
>> dd <- within(dd, Seg[x2> 0 & x3> 200] <- 1)
>
> In this instance the first of your assignments appears superfluous.
>
>> dd <- within(dd, Seg[x2> 100 & x3> 300] <- 2)
>> dd <- within(dd, Seg[x2> 200 & x3> 400] <- 3)
>> dd <- within(dd, Seg[x2> 300 & x3> 500] <- 4)
>>
>> I sthere any better way of doing it!!
>>
>
>
> dd <- with(dd, Seg <- min(findInterval(x2, c(-Inf ,100, 200, 300,  
> Inf) ),
>                          findInterval(x3, C(-Inf ,300, 400, 500,  
> Inf) )
>           )               )

Should have labeled that as an untested guess. A couple of typoes. And  
should have assigned to $Seg since I was using `with` instead  within  
as you used AND the cap C is wrong AND should have used `pmin` instead  
of 'min'

dd$Seg <- with(dat, pmin( findInterval(x2, c(-Inf,100, 200, 300,  
Inf) ) ,
                          findInterval(x3, c(-Inf ,300, 400, 500,  
Inf)  )   ) )

Tested with the dataset offered in another question yesterday:

with(dat, table( findInterval(x, c(-Inf, -2, -1.5, -1, Inf) ) ,
                    findInterval(y, c(-Inf ,0, .05, .1, Inf)  )   ) )
#---------
      1  2  3  4
   1  0  3  9 40
   2 11  9 11  5
   3 21  5  7  0
   4  6  2  1  0
#---------
  with(dat, pmin( findInterval(x, c(-Inf, -2, -1.5, -1, Inf) ) ,
                          findInterval(y, c(-Inf ,0, .05, .1,  
Inf)  )   ) )
#---------
   [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1  
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  [48] 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 1 1 2 2 2 2 2 2 2 2 2 1 1 1 1 3  
3 2 2 2 2 2 1 1 1 1 1 1 3 3 3
  [95] 2 2 2 1 1 1 1 1 1 1 3 3 2 2 1 1 1 1 1 1 1 1 1 3 2 2 1 1 1 1 1 1  
1 1 1 1

>



David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list