I have two vectors of equal length and I would like to halve the values in the first one based on a criteria from the second. As a concrete example, let
V1 = 1:6 ; V2 = c(0,0,1,1,0,1)
I would like to divide every value in V1 by 2 which corresponds to a 1 in V2.
I know how to do this using a for loop but each vector has several hundred thousand elements so it seems like there should be a much faster method.
What I am really looking for is something like the apply function but only applied to selective elements.
v1 = c(1:6)
v2 = c(0,0,1,1,0,1)
v1 / (v2+1)
More generally if you want an apply function, look at ?mapply
mapply(function(x1, x2) { if (x2==1) { x1/2; } else { x1 } } , v1, v2)
Here's a way to do it with data.table, which is likely to be fast...
library(data.table)
DT[v2==1,divisor:=2]
DT[v2==0,divisor:=1]
DT[,answer:=v1/divisor]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With