title: looping over different factor levels in a dataframe
body: <p>I have some code to take random samples of 1 to 10 rows from a data frame, replicate that random sampling 5 times and calculate a network metric (connectance) on each of the random samples. However, I would like to run this code separately over each level of "site" and "method" in my data frame. </p>
  
  <p>How do I split the data frame (df) by site and method, run the code below on each subset and then return all outputs into a single file that has the columns "site", "method", "size" (number of rows sampled) and "connectance"?</p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>df &lt;- read.table(text = "bird_sp plant_sp value site method
                    1  species_a  plant_a     1    a      m
                    2  species_a  plant_a     1    a      m
                    3  species_b  plant_b     1    a      m
                    4  species_b  plant_b     1    a      m
                    5  species_c  plant_c     1    a      m
                    6  species_a  plant_a     1    b      m
                    7  species_a  plant_a     1    b      m
                    8  species_b  plant_b     1    b      m
                    9  species_b  plant_b     1    b      m
                    10 species_c  plant_c     1    b      m
                    11 species_a  plant_a     1    a      f
                    12 species_a  plant_a     1    a      f
                    13 species_b  plant_b     1    a      f
                    14 species_b  plant_b     1    a      f
                    15 species_c  plant_c     1    a      f
                    16 species_a  plant_a     1    b      f
                    17 species_a  plant_a     1    b      f
                    18 species_b  plant_b     1    b      f
                    19 species_b  plant_b     1    b      f
                    20 species_c  plant_c     1    b      f", header = TRUE)
  
  #make sample function
  sample_fun &lt;- function(x,size){
  rows &lt;- sample(1:nrow(x),size,replace=FALSE)
  intlist &lt;- x[rows,]
  return(intlist)
  }
  
  #convert list to interaction matrix
  make_mat &lt;- function(x){
  mat &lt;- with(x,tapply(value, list(plant_sp, bird_sp), sum))
  mat[is.na(mat)] &lt;- 0
  return(mat)
  }
  
  #create vector with required sample size and replication
  size_vector &lt;- rep(1:10,5)
  
  #use vector to generate list of interactions
  samples_Data &lt;- lapply(size_vector, function(x) sample_fun(df,x))
  
  output &lt;- lapply(samples_Data, function(x)
  make_mat(x))
  
  library(bipartite)
  
  #calculate connectance on each element (matrix) in output list
  #ignore warnings
  metrics &lt;- lapply(output, networklevel, index=c("connectance"))
  met &lt;- data.frame(unlist(metrics))
  names(met) &lt;- names(metrics[[1]])
  
  #Add number of interactions sampled
  met$size &lt;- size_vector
  </code></pre>