如果只有一行,你可以否定列(如0 == FALSE):
res <- df[, !df]
或者检查colSums在哪里0:
res <- df[, colSums(df) == 0]
输出:
d e f
1 0 0 0
数据:
df <- structure(list(a = -0.00106163456888295, b = -4.11357273721094e-05,
c = -0.000181424293930435, d = 0, e = 0, f = 0), class = "data.frame", row.names = c(NA,
-1L))
基准测试显示@akrun 的Filter 是迄今为止最快的(没有包括dplyr 变体,因为它是迄今为止最慢的):
Unit: milliseconds
expr min lq mean median uq max neval
which 25.1935 26.95415 29.42942 28.00300 31.34740 181.5487 1000
== 14.2807 15.25200 16.84471 15.73310 16.92505 182.6126 1000
Filter 1.6767 1.80705 2.02523 1.90270 1.99135 7.5026 1000
colSums 11.0489 11.85425 12.83663 12.26115 13.04670 23.9469 1000
! 14.2278 15.07710 16.55270 15.55400 16.76835 187.0145 1000
基准代码:
set.seed(3234)
ncols <- 3000
df <- as.data.frame(matrix(rpois(ncols, 0.5), ncol = ncols))
bench <- microbenchmark::microbenchmark(
which = df[, which(df[1, ] == 0)],
`==` = df[, df == 0],
Filter = Filter(function(x) all(x == 0), df),
colSums = df[, colSums(df) == 0],
`!` = df[, !df],
times = 1000
)