如果该列的总和在R中等于0,则删除该列

时间:2020-07-24 20:49:53

标签: r

我创建了一个for循环来遍历火车数据集中的每一列。它检查列的绝对值之和是否等于0,如果是,它将在我的列表中存储列名“ aux”。在循环的最后,我分配火车来删除“ 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

1 个答案:

答案 0 :(得分:2)

我们可以使用Filter

而不是循环
Filter(function(x) sum(abs(x), na.rm = TRUE) > 0, train)

或与colSums

train[colSums(abs(train), na.rm = TRUE) > 0]
相关问题