识别二进制列

Pie*_*nte 10 r

我想在data.frame中识别二进制列.

例如,这个表

my.table <-read.table(text="a,b,c
0,2,0
0.25,1,1
1,0,0", header=TRUE, as.is=TRUE,sep = ",")
Run Code Online (Sandbox Code Playgroud)

会给 FALSE, FALSE, TRUE

Ben*_*ker 14

apply(my.table,2,function(x) { all(x %in% 0:1) })
Run Code Online (Sandbox Code Playgroud)

(要么

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

如果你想允许NA值)


Tom*_*mmy 5

如果你想接受其中包含 NA 的二进制列,以下应该可以解决问题:

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 
Run Code Online (Sandbox Code Playgroud)

...或者如果你只接受 0,1,NA:

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

  • 看到我上面的评论——我认为基于‘length(unique(x))==2’的“二进制”可能是危险的...... (3认同)