【问题标题】:Create a counting variable which I can use to group my unemployment data in R创建一个计数变量,我可以使用它在 R 中对失业数据进行分组
【发布时间】:2023-03-15 06:45:01
【问题描述】:

我有如下数据,我用函数创建了变量“B”:

index <- which(Count$unemploymentduration ==1)
Count$B[index]<-1:length(index)

ID unemployment B
1    1          1 
1    2          NA
1    3          NA 
1    4          NA 
2    1          2 
2    2          NA 
2    0          NA
2    1          3
2    2          NA
2    3          NA
2    4          NA
2    5          NA

我想要我的数据以这种方式并且不知道如何获得它。 想到了一个“if-function”,但从未在 R 中使用过。

ID unemployment B
1    1          1 
1    2          1
1    3          1
1    4          1
2    1          2 
2    2          2 
2    0          2
2    1          3
2    2          3
2    3          3
2    4          3
2    5          3

有人可以帮我吗?

【问题讨论】:

    标签: r panel-data


    【解决方案1】:

    我们可以从library(zoo)使用na.locf

    library(zoo)
    Count$B <- na.locf(Count$B)
    

    但是,这可以直接创建而不使用“索引”

    Count$B <- cumsum(Count$unemployment==1)
    

    【讨论】:

    • 感谢您的快速回答!这正是我想要的。
    猜你喜欢
    • 2022-01-12
    • 2015-07-21
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2020-06-11
    • 2018-05-22
    • 2022-08-04
    • 2021-12-02
    相关资源
    最近更新 更多