R-查找至少包含n个不同元素的行

时间:2018-09-28 20:44:54

标签: r

我有一个任意大小但不平凡的数据帧。每个条目具有随机分布的三个不同值0、1或2之一。例如:

col.1 col.2 col.3 col.4 ...
0     0     1     0     ...
0     2     2     1     ...
2     2     2     2     ...
0     0     0     0     ...
0     1     1     1     ...
...   ...   ...   ...   ...

我的目标是删除仅包含一个唯一元素的任何行,或仅选择具有至少两个不同元素的行。最初,我选择那些行均不是整数的行,但我意识到可以消除包含相等数量的0和2的行,而这些行我想保留。

我目前的思维过程是在数据帧的每一行上使用唯一性,然后通过长度确定每个元素包含多少个唯一元素,但我似乎无法正确理解语法。我正在寻找这样的东西

DataFrame[length(unique(DataFrame)) != 1, ]

2 个答案:

答案 0 :(得分:1)

那这样的事情呢?

# some fake data
df<-data.frame(col1 = c(2,2,1,1),
col2 = c(1,0,2,0),col3 = c(0,0,0,0))
      col1 col2 col3
1    2    1    0
2    2    0    0
3    1    2    0
4    1    0    0

# first we can convert 0 to NA
df[df == 0] <- NA

# a function that calculates the length of uniques, not counting NA as levels
fun <- function(x){
                   res <-  unique(x[!is.na(x)])
                   length(res)
                  }

# apply it: not counting na, we can use 2 as threshold
df <- df[apply(df,1,fun)>=2,]

# convert the na to 0 as original
df[is.na(df)] <- 0
df
  col1 col2 col3
1    2    1    0
3    1    2    0

答案 1 :(得分:1)

尝试以下任何一种方法

nuniq <- function(x) length(unique(x))
subset(dd, apply(dd, 1, nuniq) >= 2)

subset(dd, apply(dd, 1, sd) > 0)

subset(dd, apply(dd[-1] != dd[[1]], 1, any))

subset(dd, rowSums(dd[-1] != dd[[1]]) > 0)

subset(dd, lengths(lapply(as.data.frame(t(dd)), unique)) >= 2)

subset(dd, lengths(apply(dd, 1, table)) >= 2)

# nuniq is from above
subset(dd, tapply(as.matrix(dd), row(dd), nuniq) >= 2)

给予:

  col.1 col.2 col.3 col.4
1     0     0     1     0
2     0     2     2     1
5     0     1     1     1

nuniq的替代

在以上nuniq中,可以用以下任何一种代替:

function(x) nlevels(factor(x))

function(x) sum(!duplicated(x))

funtion(x) length(table(x))

dplyr::n_distinct

注意

dd的可复制形式为:

dd <- structure(list(col.1 = c(0L, 0L, 2L, 0L, 0L), col.2 = c(0L, 2L, 
2L, 0L, 1L), col.3 = c(1L, 2L, 2L, 0L, 1L), col.4 = c(0L, 1L, 
2L, 0L, 1L)), class = "data.frame", row.names = c(NA, -5L))
相关问题