Convert vector of 0 and 1 to binary vector in R

后端 未结 4 865
忘掉有多难
忘掉有多难 2021-01-28 07:16

It is quite surprise to me that I could not find a ready answer for this question on stackoverflow.

In R, I have a vector of 0 and 1, and I wan

相关标签:
4条回答
  • 2021-01-28 08:00

    My comment should have been an answer. You can just do:

    as.logical(c(0,1,1,0))
    
    0 讨论(0)
  • 2021-01-28 08:03

    We can use !=

    c(0,1,1,0)!=0
    #[1] FALSE  TRUE  TRUE FALSE
    
    0 讨论(0)
  • 2021-01-28 08:09

    If the object size in memory is important (TRUE or FALSE are 56 bits size) a good option is the bit package, that can turn TRUE or FALSE values in a vector in to a 1 bit values vector.

    0 讨论(0)
  • 2021-01-28 08:17

    We can use !!:

    rep(0:1, 5)
    [1] 0 1 0 1 0 1 0 1 0 1
    
    !!rep(0:1, 5)
    [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
    

    All 0s will be converted to FALSE, any other numeric to TRUE.

    0 讨论(0)
提交回复
热议问题