R: vector conditional 0 and 1

两盒软妹~` 提交于 2019-12-01 14:39:34

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.

The way r codes logical data, your vector b <- a > 2 is already (0,0,1,1) - r stores "TRUE" values as 1's and "FALSE" values as 0's. You could even take mean(b) and it would return .5. If you'd prefer to visualize numbers instead of logical values however, you could always just do b <- as.numeric(b), or to put it all in one line of code b <- as.numeric(a > 2)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!