Extracting duplicate lines from a data frame

2019-05-04 09:26发布

问题:

I have a large data frame that Im working with, the first few lines are as follows:

      Assay   Genotype   Sample    Result
1     001        G         1         0
2     001        A         2         1
3     001        G         3         0 
4     001        NA        1         NA
5     002        T         1         0
6     002        G         2         1
7     002        T         2         0 
8     002        T         4         0
9     003        NA        1         NA

In total I'll be working with 2000 samples and 168 Assays for each sample.

Id like to extract the lines where I have multiple entries with both the same Assay and Sample. I want the resulting data to be in a data frame containing all of the duplicate entries, sorted such that the duplicates are next to each other. From the example above the result would look like this:

      Assay   Genotype   Sample    Result
1     001        G         1         0
4     001        NA        1         NA
6     002        G         2         1
7     002        T         2         0 

回答1:

Demo data for easy loading:

df <- structure(list(Assay = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L), Genotype = structure(c(2L, 1L, 2L, NA, 3L, 2L, 3L, 3L, NA), .Label = c("A", "G", "T"), class = "factor"), Sample = c(1L, 2L, 3L, 1L, 1L, 2L, 2L, 4L, 1L), Result = c(0L, 1L, 0L, NA, 0L, 1L, 0L, 0L, NA)), .Names = c("Assay", "Genotype", "Sample", "Result"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"))

You could easily get the dupicated Assay/Sample pairs with duplicated:

vars <- c('Assay', 'Sample')
dup <- df[duplicated(x[, vars]), vars]

Resulting in:

> dup
  Assay Sample
4     1      1
7     2      2

Which needs a simple merge for required result:

> merge(dup, df)
  Assay Sample Genotype Result
1     1      1     <NA>     NA
2     1      1        G      0
3     2      2        G      1
4     2      2        T      0