Coerce logical (boolean) vector to 0 and 1

后端 未结 2 1295
予麋鹿
予麋鹿 2021-01-16 17:32

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         


        
2条回答
  •  我在风中等你
    2021-01-16 18:11

    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)

提交回复
热议问题