2016-04-14 73 views
0

我想通過使用Dplyr和過濾功能NA(通過在指定的列中保留NA的行)進行過濾。使用下面的代碼,只是返回沒有數據的列標籤。我是否正確編寫代碼?此外,如果沒有dplyr可能(或更容易)做到這一點也很有趣。謝謝。我怎樣才能通過N編程與Rp編程與Dplyr

filter(tata4, CompleteSolution == "NA", KeptInformed == "NA") 
+1

'tata4 [is.na(tata4&CompleteSolution)is.na(tata4 $ KeptInformed),]'假設那些各自的列。無論如何,我認爲'is.na()'是你所追求的。 – Badger

+1

使用'is.na'而不是'==「NA」',它尋找一個字符串。 – alistaire

+1

下一次,請考慮提供一個可重複的例子,正如Steven在答案的「數據」部分中所做的那樣。 – Frank

回答

4

你可以使用complete.cases()

dplyr::filter(df, !complete.cases(col1, col2)) 

其中給出:

# col1 col2 col3 
#1 NA 5 5 
#2 NA 6 6 
#3 5 NA 7 

基準

large_df <- df[rep(seq_len(nrow(df)), 10e5), ] 

迄今爲止的結果:

library(microbenchmark) 
mbm <- microbenchmark(
    akrun1 = large_df[rowSums(is.na(large_df[1:2]))!=0, ], 
    akrun2 = large_df[Reduce(`|`, lapply(large_df[1:2], is.na)), ], 
    steven = filter(large_df, !complete.cases(col1, col2)), 
    times = 10) 

enter image description here

#Unit: milliseconds 
# expr  min  lq  mean median  uq  max neval cld 
# akrun1 814.0226 924.0837 1248.9911 1208.7924 1434.2415 2057.1338 10 c 
# akrun2 499.3404 671.9900 736.2418 687.9194 861.4477 1068.1232 10 b 
# steven 112.9394 113.0604 214.1688 198.4542 299.7585 355.1795 10 a 

數據

df <- structure(list(col1 = c(1, 2, 3, 4, NA, NA, 5), col2 = c(1, 2, 
3, 4, 5, 6, NA), col3 = c(1, 2, 3, 4, 5, 6, 7)), .Names = c("col1", 
"col2", "col3"), row.names = c(NA, -7L), class = "data.frame") 
+1

明白了。謝謝。 – Stephertless

1

我們可以在邏輯矩陣使用rowSumsis.na(df[1:2])),檢查它是否不等於0以獲得邏輯向量並將其用於子集。

df[rowSums(is.na(df[1:2]))!=0,] 
# col1 col2 col3 
#5 NA 5 5 
#6 NA 6 6 
#7 5 NA 7 

或用Reducelapply

df[Reduce(`|`, lapply(df[1:2], is.na)),]