【问题标题】:Removing column/s from multiple data-frames从多个数据框中删除列
【发布时间】:2018-12-09 17:52:16
【问题描述】:

假设我有多个相同列的 data.frames,但顺序不同。我想一次从所有数据框中删除一列。例如,假设存在名为“Group 1”和“Group 2”的列。 我试过了,但失败了。

remover<-function(input){

  input<-input[,-c("Group 1","Group 2")]

  return(input)

}

另外,我看到了这个链接 (How to remove certain columns in multiple data frames in R?),不想使用列表。

任何帮助将不胜感激。

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    首先,使用带有空格的变量名不是很明智。请改用积分,例如"Group.1"

    其次,虽然c("Group 1","Group 2") 有效,但-c("Group 1","Group 2") 无效,因为您正在尝试使用字符进行算术运算:- "Group.1" 没有多大意义,不是吗?

    所以我们可以使用%in%which() 一起使用,这是一种匹配运算符,它给出了元素的索引。

    remover <- function(input) {
      input <- input[, -which(names(input) %in% c("Group.1", "Group.2"))]
      return(input)
    }
    
    x1 <- remover(df1)
    > x1
      X1 X2
    1  4 10
    2  5 11
    3  6 12
    

    还有另一个选项可以实现对 colnames 的否定,而不是 -。我们可以使用!

    remover2 <- function(input) {
      input <- input[, which(!names(input) %in% c("Group.1", "Group.2"))]
      return(input)
    }
    

    使用! 可能会有一点速度优势。

    Unit: microseconds
              expr    min     lq     mean median     uq       max neval cld
      remover(df1) 26.789 28.065 30.27720 28.321 28.831 18419.152 1e+05   a
     remover2(df1) 26.534 27.810 30.09483 28.065 28.576  6056.713 1e+05   a
    
    > all.equal(x1, x2)
    [1] TRUE
    

    数据:

    df1 <- data.frame(matrix(1:12, 
                             3, 4, 
                             dimnames=list(NULL, c("Group.1", "X1", 
                                                   "Group.2", "X2"))))
    

    【讨论】:

    • 谢谢。有效。 (尽管我曾要求删除;我在“which”前面加上了“-”)。此外,这些只是虚拟值。我的预期列名没有空格。不过谢谢你的提示。
    猜你喜欢
    • 1970-01-01
    • 2017-03-16
    • 2018-03-28
    • 2019-10-29
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多