Here is a base R method with Reduce
and intersect
.
dat[dat$year == Reduce(intersect, split(dat$year, dat$names)),]
which returns
names year
1 cody year2000
2 cody year2001
3 cody year2002
4 cody year2003
5 cody year2004
11 sam year2000
12 sam year2001
13 sam year2002
14 sam year2003
15 sam year2004
Here, we use Reduce
to repeatedly feed arguments (the separate years for each name provided as a list using split
) to intersect
, which eliminates "non-matching" years until you end up with only those years that are available for all names.
Note that the year variable has to be a character vector, not a factor variable.
As a minor simplification, you could use with
to reduce the dat$
references:
dat[with(dat, year == Reduce(intersect, split(year, names))),]
data
dat <-
structure(list(names = c("cody", "cody", "cody", "cody", "cody",
"cody", "cody", "cody", "cody", "cody", "sam", "sam", "sam",
"sam", "sam"), year = c("year2000", "year2001", "year2002", "year2003",
"year2004", "year2005", "year2006", "year2007", "year2008", "year2009",
"year2000", "year2001", "year2002", "year2003", "year2004")),
.Names = c("names", "year"), row.names = c(NA, -15L), class = "data.frame")
stringsAsFactors = FALSE
when creating data frames.