Generate a dummy-variable

前端 未结 17 1052
遇见更好的自我
遇见更好的自我 2020-11-21 11:41

I have trouble generating the following dummy-variables in R:

I\'m analyzing yearly time series data (time period 1948-2009). I have two questions:

  1. <
17条回答
  •  隐瞒了意图╮
    2020-11-21 12:28

    Hi i wrote this general function to generate a dummy variable which essentially replicates the replace function in Stata.

    If x is the data frame is x and i want a dummy variable called a which will take value 1 when x$b takes value c

    introducedummy<-function(x,a,b,c){
       g<-c(a,b,c)
      n<-nrow(x)
      newcol<-g[1]
      p<-colnames(x)
      p2<-c(p,newcol)
      new1<-numeric(n)
      state<-x[,g[2]]
      interest<-g[3]
      for(i in 1:n){
        if(state[i]==interest){
          new1[i]=1
        }
        else{
          new1[i]=0
        }
      }
        x$added<-new1
        colnames(x)<-p2
        x
      }
    

提交回复
热议问题