我正在尝试删除数据帧中仅包含值0的所有列。我在这个网站上找到的代码如下。
dataset = dataset[ ,colSums(dataset != 0) > 0]
然而,我不断返回一个错误:
[.data.frame(数据集,colSums(数据集!=0(>0(中的错误:
未定义的列选择
这是因为您至少在一列中有一个NA。修复如下:
dataset = dataset[ , colSums(dataset != 0, na.rm = TRUE) > 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)]
有一种使用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
数据
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