提取两列中因子级别的行在另一个数据帧的列中不匹配

时间:2017-08-15 20:11:30

标签: r dataframe subset

我有一个简单,正确的状态和状态代码的索引表(R中的数据帧):

statecodeconcordance<-structure(list(State.Code = structure(1:5, .Label =
c("1", "2", "3", "4", "5"), class = "factor"), State.Name = structure(1:5, 
.Label = c("Alabama", "Alaska", "Arizona", "Arkansas", "California"), class 
= "factor")), .Names = c("State.Code", "State.Name"), row.names = c(NA, 
-5L), class = c("data.table", "data.frame"))

看起来像这样:

   State.Code State.Name
1           1    Alabama
2           2     Alaska
3           3    Arizona
4           4   Arkansas
5           5 California

然后我有一个错误的数据框,其中一些状态被分配了错误的状态代码(以及各种不相关的列):

sampledata<-structure(list(State.Code = structure(c(1L, 2L, 1L, 1L, 1L, 2L,
 4L, 3L, 1L, 4L), .Label = c("1", "2", "3", "5"), class = "factor"), 
State.Name = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 3L, 3L, 4L, 4L), .Label = 
c("Alabama", "Alaska", "Arizona", "California"), class = "factor"), 
Unrelated.Data = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), 
.Label = c("some_data", "more_data", "other_data", "data_squared", 
"alternate_data", "yet_more_data", "so_much_data", 
"running_out_of_modifiers_for_data", "still_more_data", "last_data"), class 
= "factor")), .Names = c("State.Code", "State.Name", "Unrelated.Data"), 
class = "data.frame", row.names = c(NA, -10L))

看起来像这样:

   State.Code State.Name                    Unrelated.Data
1           1    Alabama                         some_data
2           2    Alabama                         more_data
3           1    Alabama                        other_data
4           1    Alabama                      data_squared
5           1    Alabama                    alternate_data
6           2     Alaska                     yet_more_data
7           5    Arizona                      so_much_data
8           3    Arizona running_out_of_modifiers_for_data
9           1 California                   still_more_data
10          5 California                         last_data

如何对后一个数据帧进行子集化,以仅返回状态代码对与一致性表中的对不匹配的行(即AlabamaState.Name的那些行,但是1中的非State.Code号码,Alaska中的State.Name2中的非State.Code号码等等?)

理想输出:

   State.Code State.Name                    Unrelated.Data
2           2    Alabama                         more_data
7           5    Arizona                      so_much_data
9           1 California                   still_more_data

2 个答案:

答案 0 :(得分:3)

您可以使用dplyr包:

library(dplyr)
anti_join(sampledata, statecodeconcordance, by = c("State.Code","State.Name"))

#   State.Code State.Name  Unrelated.Data 
# 1          5    Arizona    so_much_data 
# 2          2    Alabama       more_data 
# 3          1 California still_more_data

答案 1 :(得分:2)

我们可以使用data.table包。

library(data.table)

setDT(sampledata)
setDT(statecodeconcordance)

sampledata[!statecodeconcordance, on = c("State.Code", "State.Name")]
   State.Code State.Name  Unrelated.Data
1:          2    Alabama       more_data
2:          5    Arizona    so_much_data
3:          1 California still_more_data