0
votes

I want to recoded a variable so that, for example, we can get transforme this vector in the following way:

> a <- c(0,0,0,0,0,1,1,1,1,1) # original 
> b <- c(-5,-4,-3,-2,-1,0,1,2,3,4) # transformed
> cbind(a,b)
  a  b
 [1,] 0 -5
 [2,] 0 -4
 [3,] 0 -3
 [4,] 0 -2
 [5,] 0 -1
 [6,] 1  0
 [7,] 1  1
 [8,] 1  2
 [9,] 1  3
[10,] 1  4
>

These variables follow an order, which happen to be a time order. In the original data set, I have a variable which is coded "0" or "1", such as "a" in the example here. It is a categorical indicator for each year. At some point, there is a transition from "0" to "1", like in the row number 6 in these example. Then I would like to recoded the original variable, creating a new variable that actually tells me how many years before and after the change from "0" to "1". Thus "-5" means five year before the transition, "0" means the year of the transition and, say, "4" means four years after the transitions. Any suggestions the best way to do it? Thanks! Antonio.

1
What's the relationship between a and b? It looks like b is a sequence that starts at -5? Or do the values of a and b play into it somehow?Chase
b is what I would like to get after transforming a. This is, of course, a very simplified example of a much more complex data set.Tom
Right - but it's not clear how a and b are related. The basic strategy is to identify whatever the relationship is and then write out the relationship between the two columns using the appropriate arithmetic operators and/or other R functions.Chase
I think he means the transition point in this example is in row 6, so that is time 0, therefore row 5 is t-1, row 4 is t-2, with row 7 being t+1, row 8 being t+2. But that rule would require only one transition in the data, if there were more than one, I can't see how to program this easily, because I couldn't see the logic.Michelle

1 Answers

5
votes
> M <- matrix( c(0,0,0,0,0,1,1,1,1,1) , ncol=1)
> M <- cbind(M, seq_along(M) - min(which(M > 0)))
> M
      [,1] [,2]
 [1,]    0   -5
 [2,]    0   -4
 [3,]    0   -3
 [4,]    0   -2
 [5,]    0   -1
 [6,]    1    0
 [7,]    1    1
 [8,]    1    2
 [9,]    1    3
[10,]    1    4