title: R - Test if value is the same as the one in the cell above
body: <p>I have the following df:</p>
  
  <pre><code>name   color
  A      red 
  B      red
  C      green
  D      red
  E      red
  F      red
  </code></pre>
  
  <p>And I want to test the values in the 'color' column to see if they're the same as the values in the row above and write to a new column... I can do so using the following:</p>
  
  <pre><code>&gt; df$same &lt;- ifelse(df$color == df$color[c(NA,1:(nrow(df)-1))], 1, 0)
  </code></pre>
  
  <p>To give me:</p>
  
  <pre><code>name   color  same
  A      red      NA
  B      red       1
  C      green     0
  D      red       0
  E      red       1
  F      red       1
  </code></pre>
  
  <p>But is there a cleaner way to do it? (I use this all the time)...</p>