I have a vector v1 = c(0, 3, 5, 1, 1, 1, 3, 5, 0). How can I create a vector of equal length BUT with values -1 if 0 or 3 and 1 if 1 or 5.
So with v1 = c(0, 3, 5, 1, 1, 3, 5, 0), I am expecting a new vector:
v2 = c(-1, -1, 1, 1, 1, -1, 1, -1)
Another possibility:
v2 <- c(-1,1)[1 + (v1 %in% c(1,5))]
which gives:
> v2 [1] -1 -1 1 1 1 -1 1 -1
What this does:
v1 %in% c(1,5) creates a logical vector1 you create an integer vector of 1's and 2's.c(-1,1) which will create the required resultFor when v1 contains other numbers than 0, 1, 3 or 5 you should be more explicit:
v2 <- c(-1,1)[(v1 %in% c(0,3)) + 2*(v1 %in% c(1,5))]
In the package car is the function recode():
library("car")
v1 = c(0, 3, 5, 1, 1, 3, 5, 0)
# v2 = c(-1, -1, 1, 1, 1, -1, 1, -1)
recode(v1, "c(0, 3)=-1; else=1")
# [1] -1 -1 1 1 1 -1 1 -1
or (if you want to set NA for values not in c(0, 1, 3, 5)):
recode(v1, "c(0, 3)=-1; c(1, 5)=1; else=NA")
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