使用数据表删除仅包含 NA 的列

Vit*_*Vit 1 r data.table

有没有比这更好的方法

DT <- DT[,!apply(DT,2,function(x) all(is.na(x))), with = FALSE]
Run Code Online (Sandbox Code Playgroud)

仅在未完全用NAs填充的列上对数据表进行子集化?

谢谢

Mic*_*ico 5

基本思想是使用以下内容找到所有NA列:

na_idx = sapply(DT, function(x) all(is.na(x)))
Run Code Online (Sandbox Code Playgroud)

要将其应用于对表进行子集化,答案取决于您是要从表中删除这些列,还是计划创建一个单独的派生表;

在前一种情况下,您应该将这些列设置为NULL

DT[ , which(sapply(DT, function(x) all(is.na(x)))) := NULL]
Run Code Online (Sandbox Code Playgroud)

在后一种情况下,有几种选择:

idx = sapply(DT, function(x) !all(is.na(x)))
DT = DT[ , idx, with = FALSE] # or DT = DT[ , ..idx]

DT = DT[ , lapply(.SD, function(x) if (all(is.na(x))) NULL else x)]
Run Code Online (Sandbox Code Playgroud)

applycolSums方法将涉及矩阵转换,这可能是低效的。

这是此处以及@DavidArenburg 在上述评论中列出的案例的基准:

          method   time
1: which := NULL  1.434
2:  for set NULL  3.432
3:   lapply(.SD) 16.041
4:         ..idx 10.343
5:    with FALSE  4.896
Run Code Online (Sandbox Code Playgroud)

代码:

library(data.table)

NN = 1e7
kk = 50
n_na = 5

set.seed(021349)
DT = setDT(replicate(kk, rnorm(NN), simplify = FALSE))
DT[ , (sample(kk, n_na)) := NA_real_]

DT2 = copy(DT)

t1 = system.time(
  DT2[ , which(sapply(DT2, function(x) all(is.na(x)))) := NULL]
)

rm(DT2)
DT2 = copy(DT)

t2 = system.time({
  for (col in copy(names(DT2))) 
    if (all(is.na(DT2[[col]]))) set(DT2, , col, NULL)
})

rm(DT2)
DT2 = copy(DT)

t3 = system.time({
  DT3 = DT2[ , lapply(.SD, function(x) if (all(is.na(x))) NULL else x)]
})

rm(DT3)

t4 = system.time({
  idx = sapply(DT2, function(x) !all(is.na(x)))
  DT3 = DT2[ , ..idx]
})

rm(DT3)

t5 = system.time({
  idx = sapply(DT2, function(x) !all(is.na(x)))
  DT3 = DT2[ , idx, with = FALSE]
})

data.table(
  method = c('which := NULL', 'for set NULL', 
             'lapply(.SD)', '..idx', 'with FALSE'),
  time = sapply(list(t1, t2, t3, t4, t5), `[`, 'elapsed')
)
Run Code Online (Sandbox Code Playgroud)

  • 鉴于用例可能涉及其中*某些但不是全部*值为NA的列,使用`sapply(.SD, function(x) anyNA(x) &amp;&amp; all(is.na(x) )))` 以避免检查明显不是 `NA` 的列。 (2认同)