1

I have a data frame like this:

df <- data.frame(
  names = c(rep("cody", 10), rep("sam", 5)),
  year  = c(paste0("year",2000:2009), paste0("year",2000:2004))
)

I would like to get a resulting output like this:

df2 <- data.frame(
  names = c(rep("cody", 5), rep("sam", 5)), 
  year  = c(paste0("year",2000:2004), paste0("year",2000:2004))
)

Any ideas?

2

3 Answers 3

2

You can group by year, then filter for those years that occur twice (or however many unique names you want):

library(dplyr)

df %>% 
  group_by(year) %>% 
  mutate(name_count = n()) %>%
  ungroup() %>% 
  filter(name_count == 2) %>% 
  select(-name_count)

   names year    
   <fct> <fct>   
 1 cody  year2000
 2 cody  year2001
 3 cody  year2002
 4 cody  year2003
 5 cody  year2004
 6 sam   year2000
 7 sam   year2001
 8 sam   year2002
 9 sam   year2003
10 sam   year2004
2

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")
0

Here is an option finding all the duplicates in the year column.

df[duplicated(df$year) | duplicated(df$year, fromLast = TRUE), ]
#    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

Not the answer you're looking for? Browse other questions tagged or ask your own question.