Loop and perform operations on vector values

I have this vector:

a = c(6722, 487,  5919, 179, 7305, 336, 10015, 615,  8651, 253, 679, 75,  8652, 118, 11436, 229)

      

and I need to create a new vector with a ratio of value pairs like this:

ratio = c(a[2]/a[1], a[4]/a[3], a[6]/a[5]... etc) 

      

so the output should look like this:

ratio    num[1:8] 0.0724 0.03024 0.04599 etc   (edited)

      

I tried the following code:

ratio = c()
  for (i in length(a)){
    ratio[i] = a[2*i]/a[2*i-1]
  }

      

and got the following:

Error in a[0+2i] : invalid subscript type 'complex'

      

after i realized that R thought i meant i = sqrt (-1) i tried this:

ratio = c()
 for (i in length(a)){
    ratio[i] = a[i+i]/a[i+i-1]
  }

      

which produced:

> ratio
 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

      

then I tried with paw:

lapply(a, function(x)
    a[x+i]/a[x+i-1])

      

which gave me a 16 element list full of NA.

Does anyone know how to do this?

+3


source to share


1 answer


You don't need a loop here for

, try it (not sure what you want * 100L

at the end as your description doesn't match your desired output)



a[c(FALSE, TRUE)]/ a[c(TRUE, FALSE)] * 100L
## [1]  7.244868  3.024159  4.599589  6.140789  2.924517 11.045655  1.363847  2.002448

      

+7


source







All Articles