title: Loop function and add columns to dataframe in R
body: <p>I want to loop a function over dataframes and add information from the function to the data frame. I have read the many relevant posts on looping and applying functions to dataframes that have got me close to what I need, but not quite there, so Im hoping people can help me. </p>
  
  <p>I have a number of dataframes that look like this</p>
  
  <pre><code>dat1=as.data.frame(matrix(rnorm(25),ncol=5))
  dat2=as.data.frame(matrix(rnorm(25),ncol=5))
  dat3=as.data.frame(matrix(rnorm(25),ncol=5))
  </code></pre>
  
  <p>I want to calculate the mean of some of these columns and add on to the end of the dataframe. So, I wrote a function to calculate means from a dataframe:</p>
  
  <pre><code>my_fun &lt;-  function(dataframe){
  rowMeans( dataframe[ , c("V1","V2")],na.rm=TRUE) 
  }
  </code></pre>
  
  <p>To apply this function to one dataframe, I do this:</p>
  
  <pre><code> dat1$V6&lt;- my_fun(dat1)
  </code></pre>
  
  <p>But I want to be able to loop through all dataframes and add this mean column on to the end of each df. </p>
  
  <p>After reading some helpful posts, I created a list and used sapply:</p>
  
  <pre><code>dfList&lt;-list(dat1,dat2,dat3)#create list
  sapply(dfList, my_fun) #apply function to list
  </code></pre>
  
  <p>Which gives me the values that I want, but I dont want them in a separate output- I'd like them to simply add a column on to the original dataframe- as happens when I apply the function to the individual dataframes. Can anyone tell me how to do this? Or point me to a post that describes how to do this (I have searched high and low, but maybe typing the wrong keywords) Im sure its very straightforward if you know how!</p>