Identify binary columns

后端 未结 2 1421
悲&欢浪女
悲&欢浪女 2020-12-20 14:01

I would like to identify binary columns in a data.frame.

For example, this table

my.table <-read.table(text=\"a,b,c
0,2,0
0.25,1,1
1,0,0\", header         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 14:29

    If you want to accept binary columns with NA in them, the following should do the trick:

    is.binary <- function(v) {
      x <- unique(v)
      length(x) - sum(is.na(x)) == 2L
    }
    
    my.table <- data.frame(a=11:15, b=c(T,F,T,NA,T), c=c('foo',NA,'bar','bar','foo'))
    vapply(my.table, is.binary, logical(1))
    #    a     b     c 
    #FALSE  TRUE  TRUE 
    

    ...or if you only accept 0,1,NA:

    is.binary <- function(v) {
      x <- unique(v)
      length(x) - sum(is.na(x)) == 2L && all(x[1:2] == 0:1)
    }
    

提交回复
热议问题