title: How to predict the next column of a dataframe in R
body: <p>I have a dataframe with many columns, and for each row I want to predict what the value will be in the next column based on the values in the previous n columns.</p>
  
  <p>I can do this one row at a time using the lm() function, and I could use sapply() to loop through each row, but I'm sure there is a neater approach. </p>
  
  <p>I have also come across this question:
  <a href="https://stackoverflow.com/questions/19603239/split-on-factor-sapply-and-lm">split on factor, sapply, and lm</a> - the suggestions here would also work, but would require me to use the gather function first, and again I'm sure there must be a neater way to do this.</p>
  
  <p>The below shows a simplified, reproducible example of my data:</p>
  
  <pre><code>set.seed(0)
  my_df &lt;- data.frame(y1 = rnorm(10), y2 = rnorm(10), y3 = rnorm(10), y4 = rnorm(10), y5 = rnorm(10))
  </code></pre>
  
  <p>I could use the following code which gives me the result I'm after:</p>
  
  <pre><code>library(dplyr)
  my_df_m &lt;- sapply(1:10, FUN = function(x) {lm(as.numeric(my_df[x,1:5])~c(1:5))}[[1]][2])
  my_df %&gt;% mutate(y6 = y5 + my_df_m)
  </code></pre>
  
  <p>I could also use the following code, which requires some reformatting of my data first (apologies for the mix of data tables and frames, I confess I do not have much experience of the data.table package):</p>
  
  <pre><code>library(data.table)
  library(tidyr)
  my_df &lt;- cbind(dataSet = c(1:10), my_df)
  my_df_gather &lt;- gather(my_df, key = "x", "y", -dataSet) %&gt;%
    mutate(x = rep(1:5, each = 10))
  my_DT &lt;- data.table(my_df_gather)
  my_df %&gt;% mutate(y6 = y5 + my_DT[,list(m = lm(y~x)$coefficients[2]), by = dataSet]$m)
  </code></pre>
  
  <p>Neither approach shown above is ideal, the sapply method is fine on a small data set, but I have thousands of rows and I will need to repeat this step ~hundred times, so I would like to avoid looping to try and keep it as fast as possible.
  The second approach is probably closer to what I'm after, but requires significant reformatting of my data beforehand, which I would also like to avoid. 
  So my question is: is there a function/package that I could use on my data as it is to predict the next column, without having to loop through each row?</p>