[英]How to extract unique rows by ignoring NA's in R
我有一個包含多行和多列的數據集,我希望通過在少數情況下從一列中忽略NA來提取唯一行,並在少數情況下包括NA。 請仔細閱讀以下內容
dataset_A
e_id age fn ln custom_id
e1234 23 sur bab 1344789
e1234 23 sur bab 1344789
e1234 23 sur bab 1617
e1234 23 sur bab NA
e2345 22 nav kum NA
e2345 22 nav kum 52109
e2345 22 nav kum NA
e3456 21 ash kuma NA
e3456 21 ash kuma NA
e4567 23 anu kot NA
Expected_output
e_id age fn ln custom_id
e1234 23 sur bab 1344789
e1234 23 sur bab 1617
e2345 22 nav kum 52109
e3456 21 ash kuma NA
e4567 23 anu kot NA
基本上,如果custom_id存在於該e_id中,我想忽略來自custom_id的NA行,而如果用戶在custom_id列中只有NA值,我想保留1行並忽略其他行。
嘗試:
final_output = dataset_A[order(dataset_A$custom_id),]
final_output = final_output[!duplicated(final_output[,c(1:4)]),]
使用上面的代碼,我無法從我的數據集中提取幾行,如1617 custom_id for e_1234 e_id。 如果我們能夠找到相同的解決方案,那將非常有用。
我們可以用slice
從dplyr
通過分組e_id
如果只返回第一行all
的值custom_id
是NA
否則返回所有的非NA行,然后應用distinct
獲得獨一無二的行。
library(dplyr)
df %>%
group_by(e_id) %>%
slice(if(all(is.na(custom_id))) 1 else which(!is.na(custom_id))) %>%
distinct()
# e_id age fn ln custom_id
# <fct> <int> <fct> <fct> <int>
#1 e1234 23 sur bab 1344789
#2 e1234 23 sur bab 1617
#3 e2345 22 nav kum 52109
#4 e3456 21 ash kuma NA
#5 e4567 23 anu kot NA
也許我過度復雜的基礎R方法,但使用ave
方法
unique(df[with(df, ave(is.na(custom_id), e_id, FUN = function(x)
if (all(x)) c(TRUE, rep(FALSE, length(x) - 1)) else
replace(rep(TRUE, length(x)), x, FALSE))), ])
# e_id age fn ln custom_id
#1 e1234 23 sur bab 1344789
#3 e1234 23 sur bab 1617
#6 e2345 22 nav kum 52109
#8 e3456 21 ash kuma NA
#10 e4567 23 anu kot NA
如果理解正確,您可以使用dplyr如下:
library(dplyr)
data %>% filter (., is.na(custom_id)==FALSE) %>% distinct(.)
如果要保留NAN,可以將if if添加到slice命令
Book2 %>% group_by(., e_id) %>%
slice(., ifelse(all(is.na(custom_id)), 1 , which(!is.na(custom_id))))
編輯:有人比我快,所以請轉到上一個答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.