title: R - Comparing values in a column and creating a new column with the results of this comparison. Is there a better way than looping?
body: <p>I'm a beginner of R. Although I have read a lot in manuals and here at this board, I have to ask my first question. It's a little bit the same as <a href="https://stackoverflow.com/questions/15225038/how-can-i-compare-a-value-in-a-column-to-the-previous-one-using-r">here</a> but not really the same and i don't understand the explanation there.<br/>I have a dataframe with hundreds of thousands of rows and 30 columns. But for my question I created a simplier dataframe that you can use:</p>
  
  <pre><code>a &lt;- sample(c(1,3,5,9), 20, replace = TRUE)
  b &lt;- sample(c(1,NA), 20, replace = TRUE)
  df &lt;- data.frame(a,b)
  </code></pre>
  
  <p>Now I want to compare the values of the last column (here column <code>b</code>), so that I'm looking iteratively at the value of each row if it is the same as the in the next row. If it is the same I want to write a <code>0</code> as the value in a new column in the same row, otherwise it should be a <code>1</code> as the value of the new column.</p>
  
  <p>Here you can see my code, that's not working, because the rows of the new column only contain <code>0</code>:</p>
  
  <pre><code>m&lt;-c()
  
  for (i in seq(along=df[,1])){
      ifelse(df$b[i] == df$b[i+1],m &lt;- 0, m &lt;- 1)          
      df$mov &lt;- m
  }
  </code></pre>
  
  <p>The result, what I want to get, looks like the example below. What's the mistake? And is there a better way than creating loops? Maybe looping could be very slow for my big dataset.</p>
  
  <pre><code>   a  b mov
  1  9 NA   0
  2  1 NA   1
  3  1  1   1
  4  5 NA   0
  5  1 NA   0
  6  3 NA   0
  7  3 NA   1
  8  5  1   0
  9  1  1   0
  10 3  1   0
  11 1  1   0
  12 9  1   0
  13 1  1   1
  14 5 NA   0
  15 9 NA   0
  16 9 NA   0
  17 9 NA   0
  18 5 NA   0
  19 3 NA   0
  20 1 NA   0
  </code></pre>
  
  <p>Thank you for your help!</p>