I want to create a conditional dummy variable. Assume that I have a dataset that looks something like this:
Subject Year X X1 A 1990 1 0 A
How about this?
data$cX1 <- do.call("c",tapply(data$X1, data$Subject, FUN = function(x){ nx=length(x) #i=1 sx=c() if (nx<5) sx[1:nx]<-sum(x[1:nx]) else for(i in 1:nx)sx[i]<-sum(x[i:min(i+5-1,nx)]) sx },simplify = T)) data$Q1to3_noX1f2<-ifelse(data$Q1to3==1 & data$cX1==0,1,0)