Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new vector based on conditions from another vector

Tags:

r

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)

like image 699
Liondancer Avatar asked Nov 27 '22 13:11

Liondancer


2 Answers

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 vector
  • by adding 1 you create an integer vector of 1's and 2's.
  • you can use that as an index vector on c(-1,1) which will create the required result

For 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))]
like image 53
Jaap Avatar answered Dec 28 '22 06:12

Jaap


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")
like image 40
jogo Avatar answered Dec 28 '22 07:12

jogo