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

Berend Hasselman bhh at xs4all.nl
Tue Apr 10 10:21:46 CEST 2012


On 10-04-2012, at 08:44, aajit75 wrote:

> Hi Experts,
> 
> This may be simple question, I want to create new variable "seg" and assign
> values to it based on some conditions satisfied by each observation.
> 
> Here is the example:
> ##Below are the conditions
> 
> ##if variable x2 gt 0 and x3 gt 200 then seg should take value 1, 
> ##if variable x2 gt 100 and x3 gt 300 then seg should take value 2
> ##if variable x2 gt 200 and x3 gt 400 then seg should take value 3
> ##if variable x2 gt 300 and x3 gt 500 then seg should take value 4
> 
> id <- c(1,2,3,4,5)
> x2 <- c(200,100,400,500,600)
> x3 <- c(300,400,500,600,700)
> dd <- data.frame(id,x2,x3)
> 
> 
> dd$seg[dd$x2> 0 && dd$x3> 200] <-1
> dd$seg[dd$x2> 100 && dd$x3> 300] <-2
> dd$seg[dd$x2> 200 && dd$x3> 400] <-3
> dd$seg[dd$x2> 300 && dd$x3> 500] <-4


Use & (vector wise logical operation) instead of && (only works on first element of vector)

dd$seg[dd$x2> 0 & dd$x3> 200] <-1
dd$seg[dd$x2> 100 & dd$x3> 300] <-2
dd$seg[dd$x2> 200 & dd$x3> 400] <-3
dd$seg[dd$x2> 300 & dd$x3> 500] <-4

Berend



More information about the R-help mailing list