Fill a vector with binary values ​​using ifelse

Depending on the values ​​in the vector "p" I want to set the value in another vector to either 0 or 1. I tried the following

newvector=rep(0,length(p))
newvector=ifelse(p>=0.5,newvector=1,newvector=0)

But this generates an error that ifelse has unused arguments

Vector p

c(0.691401225261269, 0.433129612442971, 0.715983054119369, 0.886747655276408, 
0.768369966075636, 0.619451618025444, 0.747447691612602, 0.787480458130569, 
0.29095065207117, 0.703299386664627, 0.72613890310703, 0.244542050906673, 
0.424358969255879, 0.244542050906673, 0.405127250273614, 0.365573918723265, 
0.277863840689181, 0.656827737910484, 0.762318455515624, 0.839076103987831, 
0.337670440659204, 0.781335609699773, 0.815504546491645, 0.671220524010401
)
+5
source share
4 answers

You do not need to do it newvectorin advance, and using it as an argument ifelsecauses an error.

Try it...

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

But better yet, just do it with vectorization ...

newvector <- as.integer( p >= 0.5 )
+9
source

Just use:

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

The second and third arguments ifelseare not expressions, but return values.

+4
source

findInterval :

findInterval(p, .5)
+2

newvector<-round(p) ifelse.

+2

All Articles