Reputation: 315
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.
Upvotes: 0
Views: 265
Reputation: 263352
> 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
Upvotes: 5