R - find and list duplicate rows based on two columns

A simple solution is find_duplicates from hablar

library(dplyr)
library(data.table)
library(hablar)

df <- fread("
  File     T.N     ID     Col1     Col2
  BAI.txt   T      1       sdaf    eiri
  BAJ.txt   N      2       fdd     fds
  BBK.txt   T      1       ter     ase
  BCD.txt   N      1       twe     ase
            ")

df %>% 
  find_duplicates(T.N, ID)

which returns the rows with duplicates in T.N and ID:

  File    T.N      ID Col1  Col2 
  <chr>   <chr> <int> <chr> <chr>
1 BAI.txt T         1 sdaf  eiri 
2 BBK.txt T         1 ter   ase 

I have found this to be an easy and useful method.

tr <- tribble(~File,     ~TN,     ~ID,    ~Col1,     ~Col2,
              'BAI.txt',   'T',      1,       'sdaf',    'eiri',
              'BAJ.txt',   'N',     2,      'fdd',     'fds',
              'BBK.txt',   'T',      1,       'ter',     'ase',
              'BCD.txt',   'N',      1,       'twe',     'ase')

group_by(tr, TN, ID) %>% 
  filter(n() > 1)

Output:

# A tibble: 2 x 5
# Groups:   TN, ID [1]
  File    TN       ID Col1  Col2 
  <chr>   <chr> <dbl> <chr> <chr>
1 BAI.txt T         1 sdaf  eiri 
2 BBK.txt T         1 ter   ase  

Here is an option using duplicated twice, second time along with fromLast = TRUE option because it returns TRUE only from the duplicate value on-wards

dupe = data[,c('T.N','ID')] # select columns to check duplicates
data[duplicated(dupe) | duplicated(dupe, fromLast=TRUE),]

#     File T.N ID Col1 Col2
#1 BAI.txt   T  1 sdaf eiri
#3 BBK.txt   T  1  ter  ase

Tags:

R