title: Obtain column values based on changes in another column
body: <p>I have a dataframe like this:</p>
  <pre><code>dateColumnDF &lt;- c(&quot;2022-04-12 00:02:57&quot;, &quot;2022-04-12 00:02:58&quot;, &quot;2022-04-12 00:02:59&quot;, &quot;2022-04-12 00:03:00&quot;, &quot;2022-04-12 00:03:02&quot;)
  ValueColumnDf &lt;- c(&quot;50&quot;,&quot;465&quot;,&quot;788&quot;,&quot;99&quot;,&quot;25&quot;)
  Var1Df &lt;- c(&quot;0&quot;, &quot;0&quot;, &quot;0&quot;,&quot;0&quot;,&quot;0&quot;)
  Var2Df &lt;- c(&quot;0&quot;, &quot;0&quot;, &quot;1&quot;,&quot;1&quot;,&quot;0&quot;)
  Var3Df &lt;- c(&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;)
  df &lt;- data.frame(dateColumnDF, ValueColumnDf,Var1Df,Var2Df,Var3Df)
  colnames(df) &lt;- c(&quot;timestamp&quot;,&quot;Value&quot;,&quot;Var1&quot;,&quot;Var2&quot;,&quot;Var3&quot;)
  </code></pre>
  <p>And I want to obtain a dataframe that reflects the way the Varx values have been changing, from one value to another (mainly from 0 to 1 and back), like this:</p>
  <pre><code>firstColumn &lt;- c(&quot;Var2&quot;, &quot;Var2&quot;, &quot;Var3&quot;, &quot;Var3&quot;, &quot;Var3&quot;,&quot;Var3&quot;)
  secondColumn &lt;- c(&quot;1&quot;, &quot;0&quot;, &quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;)
  thirdColumn &lt;- c(&quot;2022-04-12 00:02:59&quot;, &quot;2022-04-12 00:03:02&quot;, &quot;2022-04-12 00:02:58&quot;,&quot;  
  2022-04-12 00:02:59&quot;,&quot;2022-04-12 00:03:00&quot;,&quot;2022-04-12 00:03:02&quot;)
  fourthColum &lt;- c(&quot;788&quot;,&quot;25&quot;,&quot;465&quot;,&quot;788&quot;,&quot;99&quot;,&quot;25&quot;)
  df2 &lt;- data.frame(firstColumn,secondColumn,thirdColumn,fourthColum)
  colnames(df2) &lt;- c(&quot;Var&quot;,&quot;flagChangedTo&quot;,&quot;timestamp&quot;,&quot;Value&quot;)
  </code></pre>
  <p>I have found that to see the changes in each row I need to to do (using dplyr):</p>
  <pre><code>which(df$value!= dplyr::lag(df$value))
  </code></pre>
  <p>And that I would need to put this inside a loop of the columns of interest, something like this:</p>
  <pre><code>for(i in 3:ncol(df)) {
    x &lt;- which(df[,i]!= dplyr::lag(df[,i]))
  }
  </code></pre>
  <p>After I obtain the places where it changes how can I generate the desired matrix?</p>