How to create a “conditional” variable in R?

前端 未结 2 1080
旧巷少年郎
旧巷少年郎 2021-01-27 02:15

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            


        
2条回答
  •  孤城傲影
    2021-01-27 02:59

    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)
    

提交回复
热议问题