[R] recoding one variable into another - but differently for different cases

Marc Schwartz marc_schwartz at comcast.net
Tue Jan 22 19:29:35 CET 2008


Dimitri Liakhovitski wrote:
> Hello,
> I have 2 variables in my sample Data: Data$A and Data$B
> Variable Data$A can assume values: 1, 2, 3, and 4.
> Variable Data$B identifies my cases and can assume values: 1 and 2.
> 
> I need to recode my variable Data$A into a new variable Data$new such that:
> 
> People who are Data[Data$B %in% 1, ]  are recoded like this:
> 
> Value on Data$A    Value on Data$new
> 1                             +1
> 2                             -1
> 3                             0
> 4                             99
> 
> People who are Data[Data$B %in% 2, ]  are recoded like this:
> 
> Value on Data$A    Value on Data$new
> 1                             -1
> 2                             +1
> 3                             0
> 4                             99
> 
> I am having hard time doing this. Any help would be greatly appreciated.
> Dimitri

How about this:

> Data
   A B
14 2 2
12 4 2
6  2 1
10 2 2
15 3 2
9  1 2
8  4 1
3  3 1
4  4 1
11 3 2
16 4 2
5  1 1
2  2 1
7  3 1
13 1 2
1  1 1


# Create a vector of the codes, in sequence for each subset
Codes <- c("+1", "-1", "0", "99", "-1", "+1", "0", "99")

# Create 'new' using indices into 'Codes'
Data$new <- with(Data, Codes[((B - 1) * 4) + A])

> Data
   A B new
14 2 2  +1
12 4 2  99
6  2 1  -1
10 2 2  +1
15 3 2   0
9  1 2  -1
8  4 1  99
3  3 1   0
4  4 1  99
11 3 2   0
16 4 2  99
5  1 1  +1
2  2 1  -1
7  3 1   0
13 1 2  -1
1  1 1  +1



HTH,

Marc Schwartz



More information about the R-help mailing list