Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numeric vector to binary (0/1) based on limit

Tags:

r

vector

I have a numeric vector:

p = c(0.69, 0.43, 0.72, 0.62, 0.29, 0.7)

I wish to compare the values to a limit, e.g. 0.5. If the values are equal or larger than the cut-off, the result should 1. Values less than 0.5 should become 0.

I tried ifelse, but it errors:

newvector = rep(0, length(p))
newvector = ifelse(p >= 0.5, newvector = 1, newvector = 0)
# Error in ifelse(p >= 0.5, newvector = 1, newvector = 0) : 
#   unused arguments (newvector = 1, newvector = 0)
like image 337
deemel Avatar asked Mar 22 '13 11:03

deemel


2 Answers

You don't need to make newvector beforehand and using it as an argument to ifelse is causing the error.

Try this...

newvector <- ifelse( p>=0.5 , 1 , 0 )

But even better just do it vectorised...

newvector <- as.integer( p >= 0.5 )
like image 162
Simon O'Hanlon Avatar answered Nov 15 '22 07:11

Simon O'Hanlon


Just use :

newvector <- ifelse(p>=0.5,1,0)

The second and third arguments of ifelse are not expressions but the values to be returned.

like image 39
juba Avatar answered Nov 15 '22 09:11

juba