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
501 views
in Technique[技术] by (71.8m points)

r - Coerce logical (boolean) vector to 0 and 1

I have a numeric vector:

a <- 1:4
# [1] 1 2 3 4

Check if values in 'a' is larger than 2:

a > 2
# [1] FALSE FALSE  TRUE  TRUE

However, instead of FALSE and TRUE, I want my result to be expressed as 0 and 1. Currently I am using the following method.

b <- (a > 2)
b[b == TRUE] <- 1
b[b == FALSE] <- 0

Are there any simpler methods?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There are a few ways you can go about this.

  1. Using ifelse

    b <- ifelse(a > 2, 1, 0)
    

    This is just a simpler way of writing exactly what you've written in the question: if the condition returns TRUE, set the value to 1, otherwise set it to 0.

  2. Using as.numeric

    b <- as.numeric(a > 2)
    

    Logical values can be converted to their numeric equivalents easily using this function. As one might expect, TRUE is set to 1 and FALSE to 0.

  3. The lazy version of as.numeric

    b <- 1*(a > 2)
    

    When R sees the multiplication of logical values by a numeric value, it automatically coerces the logicals to their numeric equivalents. Thus logical values can be converted lazily (from a programmer's standpoint) by multiplying by 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...