【问题标题】:Remove columns with same value from a dataframe从数据框中删除具有相同值的列
【发布时间】:2012-01-13 09:02:15
【问题描述】:

我有一个像这样的数据框

1    1    1    K    1    K    K
2    1    2    K    1    K    K
3    8    3    K    1    K    K
4    8    2    K    1    K    K
1    1    1    K    1    K    K
2    1    2    K    1    K    K

我想删除所有具有相同值的列,即K,所以我的结果会是这样的

1    1    1    1    
2    1    2    1   
3    8    3    1  
4    8    2    1  
1    1    1    1 
2    1    2    1  

我尝试在 for by 列中进行迭代,但我没有得到任何东西。有什么想法吗?

【问题讨论】:

  • 解决方案应该考虑数字以及字符/因素吗?

标签: r dataframe unique-values


【解决方案1】:

选择具有多个值的列而不考虑类型:

uniquelength <- sapply(d,function(x) length(unique(x)))
d <- subset(d, select=uniquelength>1)

?

(糟糕,Roman 的问题是对的——这也可能导致您的第 5 栏被淘汰)

也许(编辑:感谢 cmets!)

isfac <- sapply(d,inherits,"factor")
d <- subset(d,select=!isfac | uniquelength>1)

d <- d[,!isfac | uniquelength>1]

【讨论】:

  • 您的子集对我不起作用。也许d[, !isfac | uniquelength != 1]
  • ...我现在“记得”(?subset),subsetrows 上工作。为了避免这种情况,应该明确指定select,所以subset(d, select = !isfac | uniquelength &gt; 1)。 @user976991,试试看。
【解决方案2】:

这里有一个解决方案,可以删除任何重复的列(包括,例如,成对的重复字符、数字或因子列)。这就是我阅读 OP 问题的方式,即使是误读,这似乎也是一个有趣的问题。

df <- read.table(text=" 
1    1    1    K    1    K    K
2    1    2    K    1    K    K
3    8    3    K    1    K    K
4    8    2    K    1    K    K
1    1    1    K    1    K    K
2    1    2    K    1    K    K")

# Need to run duplicated() in 'both directions', since  it considers
# the first example to be **not** a duplicate.
repdCols <- as.logical(duplicated(as.list(df), fromLast=FALSE) + 
                       duplicated(as.list(df), fromLast=TRUE))
# [1] FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE

df[!repdCols]
#   V1 V2 V3 V5
# 1  1  1  1  1
# 2  2  1  2  1
# 3  3  8  3  1
# 4  4  8  2  1
# 5  1  1  1  1
# 6  2  1  2  1

【讨论】:

    【解决方案3】:

    另一种方法是使用高阶函数Filter。这是代码

    to_keep <- function(x) any(is.numeric(x), length(unique(x)) > 1)
    Filter(to_keep, d)
    

    【讨论】:

      【解决方案4】:

      Oneliner 解决方案。

      df2 <- df[sapply(df, function(x) !is.factor(x) | length(unique(x))>1 )]
      

      【讨论】:

        猜你喜欢
        • 2014-12-15
        • 2020-11-17
        • 2022-12-06
        • 2018-08-18
        • 1970-01-01
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多