从data.table中删除仅包含NA的行

时间:2016-07-22 11:31:42

标签: r data.table

我想从仅包含NA的data.table中删除这些行。

> 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

通常情况下,我会使用apply(dat, 1, ...),但不幸的是,它不能用于data.table,但它会让我找到这个不优雅的解决方案:

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

如何在不知道列名的情况下以最快的方式实现这一目标?

3 个答案:

答案 0 :(得分:3)

我们可以将// select all from table emo_cons that contain character values and image location $emocom = mysqli_query($con,"SELECT * FROM `emo_cons`"); // fetch rows from query while($emo_row= mysqli_fetch_assoc($emocom)) { // assign chars row characters that represent the coresponding image $chars = $emo_row['chars']; // assign imagetag to row images that represent the coresponding characters $imagetag = "<img width='50' class=image height='50' src='chaticons/".$emo_row['image']."' />"; echo " "; echo "<br>"; } // end while emo_car check $chat_log = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC"); // fetch all rows that contain characters and image locations while($chat_row = $chat_log ->fetch_array()){ // i WANT THIS WHILE LOOP TO OUTPUT ALL ROWS THAT CONTAIN CHARS & IMAGES-LOCATIONS // name of user in chat log $username = $chat_row['username']; // this line is for usrer echo "<br>"; // timestamp echo $chat_row['date']; echo "<br>"; // line break //users profiler avatar image from chat_row while echo "<img width='50' class=image height='50' src='avatars/".$chat_row['imagelocation']."' alt='Profile Pic'>"; echo " "; // space // THIS LINE ONLY OUTPUTS THE LAST ROW OF AN ICON IN THE TABLE // I would like my while to output all rows that contain str_replace chars TO imagetag from its table AND HAVE IT THEN PARSE TO THE MESSAGE [msg] echo $username. " Says ".$new_str = str_replace($chars,$imagetag,$chat_row['msg']); echo "<br>"; } // end while chat_log echo '</div>'; // end div ?> Reduceis.na

一起使用
&

或者是一种紧凑但不那么有效的方法

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

另外,正如@Frank评论的那样,基于联接的方法,

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

答案 1 :(得分:2)

另一个想法:

library(dplyr)
df %>% 
  filter(rowSums(is.na(.)) < length(.))

答案 2 :(得分:0)

我非常喜欢

tab <- tab[sapply(1:nrow(tab), function(i){!all(is.na(tab[i,]))}),]

对我来说很直观,但我不确定这是最快的方法。

HTH