【问题标题】:R - find rows with at least n distinct elementsR - 找到至少有 n 个不同元素的行
【发布时间】:2018-09-28 20:44:54
【问题描述】:

我有一个任意但非平凡大小的数据框。每个条目具有随机分布的三个不同值 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, ]

【问题讨论】:

  • 肯定是骗子,但您可以使用rowSums(d == d[ , 1]) == ncol(d) 查找所有值都相等的行。否定“仅选择具有至少两个不同元素的行”。

标签: r


【解决方案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))

【讨论】:

    【解决方案2】:

    这样的事情怎么样:

    # 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
    

    【讨论】:

      猜你喜欢
      • 2017-03-15
      • 2017-08-02
      • 2023-04-03
      • 2011-04-14
      • 2014-11-28
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多