【问题标题】:Drop a column if the sum of that column equals 0 in R如果该列的总和在 R 中等于 0,则删除该列
【发布时间】:2020-07-24 20:49:53
【问题描述】:

我创建了一个 for 循环来遍历我的训练数据集中的每一列。它检查列值的绝对和是否等于 0,如果是,它会将列名存储在我的名为“aux”的列表中。在循环结束时,我分配 train 以删除“aux”中的列。

问题:我不断收到错误消息“-aux 中的错误:一元运算符的参数无效”

关于数据集的注意事项:没有 NA 或 NaN,所有值都是数字。目前它是一个矩阵,但如果需要,我可以转换为一个数据框。

aux = NULL #auxiliary vector
for(i in 1:ncol(train)){ #checking all columns of the df
  
  if(sum(abs(train[,i]))==0){ #if the sum of the column is zero (using absolute value to avoid problems where the positive and negative numbers sum to zero)
    
    aux = c(aux,i) #then store the number of that column
    
  }
  
}


train = train[,-aux] #and remove the columns

【问题讨论】:

  • 您的错误表明aux 仍然是NULL,因此您的所有列都不会加到0。请注意,您正在对绝对值求和,因此aux 只会在以下情况下附加i整列为零。在这种情况下,您的整个循环可以替换为 train[sapply(train, function(x) !all(x == 0)),]
  • 你是对的,当你发表评论时我已经注意到了这个问题哈哈。所以现在我有一个新问题。最后一行代码train = train[,-aux] 将删除数据集中的所有变量,而不仅仅是 aux 中的变量。

标签: r


【解决方案1】:

我们可以使用Filter代替循环

Filter(function(x) sum(abs(x), na.rm = TRUE) > 0, train)

colSums

train[colSums(abs(train), na.rm = TRUE) > 0]

【讨论】:

  • 这非常有效。我使用了您提供的第二个选项。知道如何在测试数据集中删除相同的列吗?我曾考虑为此目的制作 for 循环,但之前并没有奏效,所以我知道我写错了。
  • @RehankhanDaya 您可以使用i1 <- colSums(abs(train), na.rm = TRUE) > 0 获取逻辑向量,并可用于获取列名。即names(which(i1)) 或删除的列names(which(!i1))
猜你喜欢
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2016-01-02
  • 2016-03-03
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多