title: loop through and perform operations with values of a vector
body: <p>I have this vector:</p>
  
  <pre><code>a = c(6722, 487,  5919, 179, 7305, 336, 10015, 615,  8651, 253, 679, 75,  8652, 118, 11436, 229)
  </code></pre>
  
  <p>and I need to create a new vector with the ratio of pairs of values like this:</p>
  
  <pre><code>ratio = c(a[2]/a[1], a[4]/a[3], a[6]/a[5]... etc) 
  </code></pre>
  
  <p>so the output should look like this:</p>
  
  <pre><code>ratio    num[1:8] 0.0724 0.03024 0.04599 etc   (edited)
  </code></pre>
  
  <p>I tried the following code:</p>
  
  <pre><code>ratio = c()
    for (i in length(a)){
      ratio[i] = a[2*i]/a[2*i-1]
    }
  </code></pre>
  
  <p>and got this: </p>
  
  <pre><code>Error in a[0+2i] : invalid subscript type 'complex'
  </code></pre>
  
  <p>after I figured out that R thought I meant i = sqrt(-1), I tried this:</p>
  
  <pre><code>ratio = c()
   for (i in length(a)){
      ratio[i] = a[i+i]/a[i+i-1]
    }
  </code></pre>
  
  <p>which produced:</p>
  
  <pre><code>&gt; ratio
   [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
  </code></pre>
  
  <p>then I tried with lapply:</p>
  
  <pre><code>lapply(a, function(x)
      a[x+i]/a[x+i-1])
  </code></pre>
  
  <p>which gave me a 16-element list full of NAs.</p>
  
  <p>Does anyone know how to do this?</p>