重新编码变量

发布于 2024-12-20 00:35:10 字数 527 浏览 2 评论 0原文

我想重新编码一个变量,例如,我们可以通过以下方式转换这个向量:

> 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
>

这些变量遵循一个顺序,而这个顺序恰好是一个时间顺序。在原始数据集中,我有一个编码为“0”或“1”的变量,例如此处示例中的“a”。它是每年的分类指标。在某个时刻,会出现从“0”到“1”的转换,就像这些示例中的第 6 行一样。然后我想重新编码原始变量,创建一个新变量,它实际上告诉我从“0”到“1”的变化前后有多少年。因此,“-5”表示过渡前五年,“0”表示过渡年份,“4”表示过渡后四年。有什么建议最好的方法吗?谢谢!安东尼奥.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三生殊途 2024-12-27 00:35:10
> 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
> 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文