Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

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

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...