Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

r - Remove lines with only NAs from data.table

I want to remove the lines from a data.table that only contain NAs.

> tab = data.table(A = c(1, NA, 3), B = c(NA, NA, 3))
> tab
    A  B
1:  1 NA
2: NA NA
3:  3  3

Normally I would do it with apply(dat, 1, ...) which unfortunately does not work on a data.table but it leads me to this inelegant solution:

> tab[apply(as.data.frame(tab), 1, function(x) !all(is.na(x))), ]
   A  B
1: 1 NA
2: 3  3

How can this be achieved the fastest way without knowing the column names?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use Reduce with is.na and &

tab[!Reduce(`&`, lapply(tab, is.na))]
#   A  B
#1: 1 NA
#2: 3  3

Or a compact but not so efficient approach would be

tab[rowSums(!is.na(tab)) != 0L]

Also, as commented by @Frank, a join based approach,

tab[!tab[NA_integer_], on = names(tab)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...