【问题标题】:Creating dummy variable in R for panel data which is sensitive to past years在 R 中为对过去几年敏感的面板数据创建虚拟变量
【发布时间】:2019-01-12 01:26:43
【问题描述】:

所以本质上我希望在 R 中创建一个变量(我们称之为 historyD),如果面板数据中的另一个虚拟变量(我们称之为 currentD)== 1,则 == 1,如果是 currentD,则 == 1 == 1 对于每个参与者特定的过去几年。棘手的部分是我的数据按参与者和降序排序,所以我希望它看起来像这样:

很难将代码与每个参与者匹配,因此 historyD 依赖于每个参与者特定的当前和过去一年 currentD。到目前为止进展甚微。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

标签: r variables time-series panel


【解决方案1】:

如果你的数据确实是Participant升序,然后Year降序,首先你可以按Participant升序排序em> 然后按升序顺序

# creation of dataframe
Participant <- factor(rep(c(1,2,3), each = 4))
Year <- rep(c(4,3,2,1), 3) #descending order of the years
currentD <- c(0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1) #data rearranged to fit your data
DF <- data.frame(Participant, Year, currentD)

# reorder the DF with participant and year in ascending order
DF <- DF[  with(DF, order(Participant, Year)),   ]

# cumulative sum by group of *Participant*
DF$historyD <- unlist(by(DF$currentD, DF$Participant, cumsum))

# All numbers higher than 1 are reset to 1
DF[DF$historyD >1, "historyD"] <- 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2023-03-24
    • 2016-06-01
    • 2015-01-29
    • 2018-10-01
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多