title: How can I use R to loop over levels of two factors
body: <p>I am trying to code a factor variable to track between-year changes in another factor variable in R.</p>
  
  <p>Suppose I have to following data strucutre:</p>
  
  <pre><code>df&lt;-data.frame(id&lt;-rep(seq(from=1,to=5,by=1),5), 
            year&lt;-c(rep(2002,5), rep(2004,5), rep(2006,5), rep(2008, 5), 
                    rep(2010, 5)), factor&lt;-rbinom(n=25,size=1,prob=0.5))
  
  colnames(df)&lt;-c("id", "year", "factor1")
  
  df[,1]&lt;-as.factor(as.character(df[,1]))
  
  df[,2]&lt;-as.factor(as.character(df[,2]))
  
  df[,3]&lt;-as.factor(as.character(df[,3]))
  
  factor2&lt;-c()
  </code></pre>
  
  <p>The Loop structure is as follows:</p>
  
  <pre><code>for(i in levels(df[,1])){
    for(j in levels(df[,2])){
      if(df[,3]&gt;0){factor2&lt;-1}
      else(factor2&lt;-0)
    }
  }
  </code></pre>
  
  <p>Which returns:</p>
  
  <blockquote>
    <p>factor2 as a numeric vector with 0 elements</p>
  </blockquote>
  
  <p>My question is, how can I get this loop structure to work?</p>