Search code examples
rmatrixrowunique

How to keep the true uniques row?


Here an example of a matrix,

A B C
1 1 1
1 1 4
1 2 4
2 1 1
3 1 1
3 1 2

I would like extract only rows which are unique in A and B. I can't use unique, duplicate etc. because they retain always one of my duplicated row.

In final result I wish obtain:

A B C
1 2 4
2 1 1

How can I do it? Thank you


Solution

  • Here are couple of options -

    1. Base R -
    cols <- c('A', 'B')
    res <- df[!(duplicated(df[cols]) | duplicated(df[cols], fromLast = TRUE)), ]
    res
    
    #  A B C
    #3 1 2 4
    #4 2 1 1
    
    1. dplyr -
    library(dplyr)
    df %>% group_by(A, B) %>% filter(n() == 1) %>% ungroup
    
    # A tibble: 2 x 3
    #      A     B     C
    #  <int> <int> <int>
    #1     1     2     4
    #2     2     1     1