找到R中面板数据发生事件的年份

时间:2016-11-06 06:57:42

标签: r

在处理由面板数据构建的数据框时有疑问

firm<-c("1","1","1","1","1","2","2","2","3","3","3","3")
year<-c("2001","2002","2003","2004","2005","1998","1999","2000","2004","2005","2006","2007")
event<-c("yes","yes","yes","no","no","yes","yes","no","yes","no","no","no")
df<-data.frame("firm"= firm,"year"= year, "event" = event)

我想要的是:

firm<-c("1","1","1","1","1","2","2","2","3","3","3","3")
year<-c("2001","2002","2003","2004","2005","1998","1999","2000","2004","2005","2006","2007")
event<-c("yes","yes","yes","no","no","yes","yes","no","yes","no","no","no")
event.year<-c("2004","2004","2004","2004","2004","2000","2000","2000","2005","2005","2005","2005")
df<-data.frame("firm"= firm,"year"= year, "event" = event,"event.year" = event.year)

问题是如何生成列“event.year”?

1 个答案:

答案 0 :(得分:2)

firm<-c("1","1","1","1","1","2","2","2","3","3","3","3")
year<-c("2001","2002","2003","2004","2005","1998","1999","2000","2004","2005","2006","2007")
event<-c("yes","yes","yes","no","no","yes","yes","no","yes","no","no","no")
df<-data.frame("firm"= firm,"year"= year, "event" = event)

library(plyr)
df1 = ddply(df, .(firm), mutate, event.year = year[which(event=="no")[1]])