Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly Divide specific values R

Tags:

r

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.

like image 753
sean ericson Avatar asked Dec 08 '25 09:12

sean ericson


1 Answers

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]
like image 131
nsheff Avatar answered Dec 09 '25 23:12

nsheff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!