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

David Winsemius dwinsemius at comcast.net
Tue Apr 10 14:59:09 CEST 2012


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) )
            )               )


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list