R:根据条件比较和过滤两个data.frames

时间:2014-09-23 17:38:18

标签: r filter compare dataframe matching

我有data.frame data_qual,如下所示:

data_qual <- structure(list(NAME = structure(1:3, .Label = c("NAME1", "NAME2", "NAME3"), class = "factor"), ID = c(56L, 47L, 77L), YEAR = c(1990L, 2007L, 1899L), VALUE = structure(c(2L, 1L, 1L), .Label = c("ST", "X"), class = "factor")), .Names = c("NAME", "ID", "YEAR", "VALUE"), class = "data.frame", row.names = c(NA, -3L))

 NAME   ID YEAR    VALUE
1 NAME1 56 1990     X
2 NAME2 47 2007    ST
3 NAME3 77 1899    ST

我想通过将data_qual与另一个数据框dat进行比较来过滤掉dat <- structure(list(NAME = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("NAME1","NAME2"), class = "factor"), ID = c(56L, 56L, 56L, 47L, 47L, 47L, 47L), YEAR = c(1988L, 1989L, 1991L, 2005L, 2006L, 2007L, 2008L), VALUE = c(45L, 28L, 28L, -12L, 14L, 23L, 32L)), .Names = c("NAME", "ID", "YEAR", "VALUE"), class = "data.frame", row.names = c(NA, -7L)) NAME ID YEAR VALUE 1 NAME1 56 1988 45 2 NAME1 56 1989 28 3 NAME1 56 1991 28 4 NAME2 47 2005 -12 5 NAME2 47 2006 14 6 NAME2 47 2007 23 7 NAME2 47 2008 32 中的值:

data_qual

如何根据列ID过滤data.frame,以便在第一个过滤过程中,只将行写入与ID匹配的新dat NAME ID YEAR VALUE 1 NAME1 56 1990 X 2 NAME2 47 2007 ST

YEAR

然后在那之后我正在寻找一种方法,从结果data.frame中只写出每行没有相同ID的行(由 NAME ID YEAR VALUE 1 NAME1 56 1990 X 定义)< / p>

{{1}}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

第一部分

dat2 <- data_qual[data_qual$ID %in% dat$ID, ]
dat2
   NAME ID YEAR VALUE
1 NAME1 56 1990     X
2 NAME2 47 2007    ST

然后是第二部分

good_rows <- lapply(paste(dat2$ID, dat2$YEAR, sep = ":"), grepl, x = paste(dat$ID, dat$YEAR, sep = ":"))
dat3 <- dat2[!unlist(lapply(good_rows, any)), ]

或者,如果这对你来说太乱,那就是for循环

good_rows <- vector(length = nrow(dat2))
for (i in 1:nrow(dat2)) {
   good_rows[i] <- !any(grepl(dat2$YEAR[i], dat[dat$ID == dat2$ID[i], "YEAR"]))
}
dat3 <- dat2[good_rows, ]
dat3
   NAME ID YEAR VALUE
1 NAME1 56 1990     X