Quickly Split Specific R Values
I have two vectors of equal length and I would like to halve the values ββin the first based on 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 each value in V1 by 2, which corresponds to 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'm really looking for is similar to the apply function, but only applies to selectable items.
source to share
v1 = c(1:6) v2 = c(0,0,1,1,0,1) v1 / (v2+1)
In general, if you want to apply a function take a look ?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 will probably be fast ...
library(data.table)
DT[v2==1,divisor:=2]
DT[v2==0,divisor:=1]
DT[,answer:=v1/divisor]
source to share
v1 <- c(1:6)
v2 <- c(0,0,1,1,0,1)
v1 / (v2 + 1)
#[1] 1.0 2.0 1.5 2.0 5.0 3.0
To use the strategy of applying a function to selected items, you need to convert v2
to a boolean vector and use it for a subset:
as.logical(v2)
#[1] FALSE FALSE TRUE TRUE FALSE TRUE
res <- v1
res[as.logical(v2)] <- res[as.logical(v2)] / 2
res
#[1] 1.0 2.0 1.5 2.0 5.0 3.0
res[as.logical(v2)]
#[1] 1.5 2.0 3.0
source to share