删除全部为0的列

问题描述 投票:0回答:3

我试图删除我的数据框中仅包含值0的所有列。我的代码是我在本网站上找到的以下代码。

dataset = dataset[ ,colSums(dataset != 0) > 0]

但是,我一直都会返回一个错误:

[.data.frame(dataset,,colSums(dataset!= 0)> 0)中的错误: 选择了未定义的列

r
3个回答
3
投票

这是因为你在至少一列中有一个NA。修复如下:

dataset = dataset[ , colSums(dataset != 0, na.rm = TRUE) > 0]

0
投票

这里有一些代码可以检查哪些列是数字(或整数),并删除包含全零和NA的列:

# example data
df <- data.frame( 
        one = rep(0,100), 
        two = sample(letters, 100, T), 
        three = rep(0L,100), 
        four = 1:100,
        stringsAsFactors = F
      )

# create function that checks numeric columns for all zeros
only_zeros <- function(x) {
    if(class(x) %in% c("integer", "numeric")) {
        all(x == 0, na.rm = TRUE) 
    } else { 
        FALSE
    }
}

# apply that function to your data
df_without_zero_cols <- df[ , !sapply(df, only_zeros)]

0
投票

有一个替代使用all()

dataset[, !sapply(dataset, function(x) all(x == 0))]
  a  c  d f
1 1 -1 -1 a
2 2  0 NA a
3 3  1  1 a

对于大型数据集,可以通过引用删除列来避免时间和内存消耗复制

library(data.table)
cols <- which(sapply(dataset, function(x) all(x == 0)))
setDT(dataset)[, (cols) := NULL]
dataset

   a  c  d f
1: 1 -1 -1 a
2: 2  0 NA a
3: 3  1  1 a

Data

dataset <- data.frame(a = 1:3, b = 0, c = -1:1, d = c(-1, NA, 1), e = 0, f ="a")
dataset
  a b  c  d e f
1 1 0 -1 -1 0 a
2 2 0  0 NA 0 a
3 3 0  1  1 0 a
© www.soinside.com 2019 - 2024. All rights reserved.