【发布时间】: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