title: Equivalent of index and match in R
body: <p>I've been looking at previous solutions to an equivalent of excel's index and match, and can't get any to work with my data in R.
  I've provided an example dataset below. There are 4 samples and measurements are a frequency count of 'CAGs' i.e. in sample A01 there are 6485 counts of 13 CAGs. I've managed to calculate the modal CAG (value in CAG for the highest measurement in each column). I've also managed to calculate summary stats on the data using psych(). I'm then using these results to calculate skewness using (mean-mode)/sd. 
  Each sample has a control sample e.g. A02's control sample is A01. I'd also like to calculate skewness using the control mode i.e. (mean-ctrlmode)/sd. To achieve this I need to look up and return the mode of the control sample into the results table. I've indicated below where I'm stuck. Would be grateful for your help!</p>
  
  <pre><code>#Data set
  data &lt;- data.frame(CAG = c(13, 14, 15, 17), 
                 A01 = c(6485,35,132, 12), 
                 A02 = c(0,42,56, 4),
                 A03 = c(33,5014,2221, 18),
                 A04 = c(106,89,436, 11))
  
  settings &lt;- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     control = c('A01', 'A01', 'A03', 'A03')) 
  
  #Mode
  samplemode &lt;- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                 samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))
  
  #Summary statistics
  sumstats &lt;- sapply(data[, 2:ncol(data)], function(x) {
    data_e &lt;- rep(data$CAG, x)
    library(psych)
    data.frame(
      describe(data_e)
    )
  })
  
  sumstats &lt;- as.data.frame(t(sumstats))
  
  sumstats[] &lt;- lapply(sumstats, function(x) {
    as.numeric(x)
  })
  
  # Results table
  results &lt;- data.frame(samples = settings$samples, 
                    samplemode = samplemode$samplemode, 
                    control = settings$control, 
                   ctrlmode = samplemode$samplemode[results$controls =     samplemode$samples], #THIS IS WHERE I'M HAVING TROUBLE
                    sumstats)
  
  
  # Skewness
  results$skewmode &lt;- (results$mean - results$samplemode) / results$sd
  results$skewctrlmode &lt;- (results$mean - results$ctrlmode) / results$sd
  
  #Expected results
  expected &lt;- data.frame(samples = settings$samples,
                     skewmode = c(0.1565726, -0.4903837, 0.6321606, -0.5270822), 
                     skewctrlmode = c(0.1565726, 2.4519186, 0.6321606, 0.6857736))
  </code></pre>