简体   繁体   中英

Convert vector of 0 and 1 to binary vector in R

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 want to convert it to binary vector, with 0 becomes F and 1 becomes T .

How could I do that?

Thanks

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

as.logical(c(0,1,1,0))

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 .

We can use !=

c(0,1,1,0)!=0
#[1] FALSE  TRUE  TRUE FALSE

如果内存中的对象大小很重要(TRUE或FALSE为56位大小),则位封装是一个不错的选择,它可以将向量中的TRUE或FALSE值转换为1位值向量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM