从基于另一个数据框的数据框中删除行

时间:2020-02-11 16:35:30

标签: r dataframe

我有一个数据框A,其中包含国家/地区列表:

Country
Hong Kong
Ireland
Thailand

元素更多,但我现在只使用三个。

我还有另一个数据框B,其中:

Country_Name      ID
France            3
France            NA
Japan             7
Korea             1
Hong Kong         18
Indonesia         NA
Japan             NA
Hong Kong         53

我现在要做的是,比较数据框B 中的国家/地区列表数据框A中的国家/地区。 < / p>

如果数据框B中的国家/地区未在数据框A中列出,并且 ID列不是NA ,则将其保留,否则将其删除。因此,结果数据框为:

Country_Name      ID
France            3
Japan             7
Korea             1
Hong Kong         18
Hong Kong         53

法国数据框B 中有两行,并且由于法国不在数据框A 中,所以如果在法国的ID列中存在不适用的任何行,该行已已删除香港在数据框A中存在,因此它仍将保留。

我尝试过类似的事情:

df_B[!df_B$Country_Name %in% df_A$Country & !na.omit(df_B$ID),]

但是问题是,在结果数据框中将省略香港。

2 个答案:

答案 0 :(得分:4)

我们需要na.omit来代替is.na,因为is.na返回逻辑向量,而na.omit除去了NA元素,从而在{{1} }

length

或使用df_B[df_B$Country_Name %in% df_A$Country|(!df_B$Country_Name %in% df_A$Country & !is.na(df_B$ID)),]

subset

数据

subset(df_B, Country_Name %in% df_A$Country|
       !(Country_Name %in% df_A$Country) & !is.na(ID))
#  Country_Name ID
#1       France  3
#3        Japan  7
#4        Korea  1
#5    Hong Kong 18
#8    Hong Kong 53

答案 1 :(得分:2)

这是dplyr版本。写的时间更长一点,但更容易阅读(IMO):

library(tidyverse)

df_B %>%
    filter(!is.na(ID)) %>% # keep rows where ID is not NA
    anti_join(df_A, by = c("Country_Name" = "Country")) # remove rows that are not in df_A