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