2016-11-06 40 views
-1

與面板數據構成的數據幀打交道時,有一個問題,尋找當年當一個事件發生在R A面板數據

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

回答

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]]) 
+0

謝謝joel,這確實有效。 –

+0

或使用'match'即'df%>%group_by(公司)%>%mutate(event.year = year [match('no',event)])' – akrun

+0

你會介意接受答案'http:// stackoverflow.com /幫助/人,answers' –

相關問題