如何标识包含二进制表示形式的所有列



有一个这样的数据帧:

dframe <- data.frame(id = c(1,2,3), Google = c(2,1,1), Yahoo = c(0,1,1), Amazon = c(1,1,0))

如何测试每列是否包含二进制(0 和 1(表示形式(每行中的最大数量不大于 1(

colname, binary_status
Google, False
Yahoo, True
Amazon, True

我们可以将colSumsstack一起使用

stack(colSums(dframe[-1] > 1) == 0)
#  values    ind
#1  FALSE Google
#2   TRUE  Yahoo
#3   TRUE Amazon

使用dplyr的其他一些方法

library(dplyr)
dframe %>% summarise_at(-1, ~all(. < 2)) 

或使用apply

!apply(dframe[-1] > 1, 2, any)

一种tidyverse的方法:

dframe %>% 
purrr::map_lgl(~all(.x %in% c(0,1)))
id Google  Yahoo Amazon 
FALSE  FALSE   TRUE   TRUE 

或者,如果您希望采用确切的格式:

dframe %>% 
purrr::map_lgl(~all(.x %in% c(0,1))) %>% 
.[-1] %>% 
as.data.frame() %>%  
setNames("values")
values
Google  FALSE
Yahoo    TRUE
Amazon   TRUE

您可以创建自己的 fnction:

is_binary <- function(x) length(unique(x)) == 2

sapply(dframe, is_binary)
#id Google  Yahoo Amazon 
#FALSE   TRUE   TRUE   TRUE 

如果您实际上正在寻找01二进制文件,您可以执行以下操作:

is_binary <- function(x) all(unique(x) %in% c(0, 1))
sapply(dframe, is_binary)
#  id Google  Yahoo Amazon 
#FALSE  FALSE   TRUE   TRUE 

一个选项是

dframe[!Reduce(`|`, lapply(dframe[-1], `>`, 0)),]
apply(my.table,2,function(x) { all(na.omit(x) %in% 0:1) })

应该工作

学分: 本 标识二进制列

你也可以使用 grep 和 length 进行比较:

is_binary<- function(x) {length(grep(1, x))+length(grep(0, x))==nrow(dframe)}
sapply(dframe,is_binary)
#id    Google  Yahoo Amazon 
#FALSE  FALSE   TRUE   TRUE  

相关内容

最新更新