简体   繁体   中英

recoding variables

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.

> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM