Identify binary columns

流过昼夜 提交于 2019-12-01 14:36:57

问题


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=TRUE, as.is=TRUE,sep = ",")

would give FALSE, FALSE, TRUE


回答1:


apply(my.table,2,function(x) { all(x %in% 0:1) })

(or

apply(my.table,2,function(x) { all(na.omit(x) %in% 0:1) })

if you want to allow for NA values)




回答2:


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)
}


来源:https://stackoverflow.com/questions/9830963/identify-binary-columns

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