Сохранить уникальные строки в R - PullRequest
1 голос
/ 27 мая 2020

Я хочу сохранить строки с одинаковыми элементами в фрейме данных, которые присутствуют в двух заданных столбцах, например

df <- data.frame(BGC1 = c("BGC1", "BGC1", "BGC1", "BGC2", "BGC2", "BGC2", "BGC3", "BGC3", "BGC3", "BGC4", "BGC4", "BGC4"),
                                     BGC2 = c("BGC2", "BGC3", "BGC4", "BGC1", "BGC3", "BGC4", "BGC1", "BGC2", "BGC4", "BGC1", "BGC2", "BGC3"),
                                     Family1 = c("Strepto_10","Strepto_20","Strepto_30", "Strepto_20","Strepto_20", "Strepto_50", "Strepto_20", "Strepto_30", "Strepto_30", "Strepto_30", "Strepto_50", "Strepto_40")
                                   , Family2 = c("Strepto_10","Strepto_10","Strepto_10", "Strepto_20","Strepto_20", "Strepto_20", "Strepto_30", "Strepto_30", "Strepto_30", "Strepto_40", "Strepto_40", "Strepto_40"))

Пример DF

BGC1  | BGC2  | Bacteria1    |   Bacteria2
BGC1    BGC2    Strepto_10       Strepto_10
BGC1    BGC3    Strepto_20       Strepto_10
BGC1    BGC4    Strepto_30       Strepto_10
BGC2    BGC1    Strepto_20       Strepto_20
BGC2    BGC3    Strepto_20       Strepto_20
BGC2    BGC4    Strepto_50       Strepto_20
BGC3    BGC1    Strepto_20       Strepto_30
BGC3    BGC2    Strepto_30       Strepto_30
BGC3    BGC4    Strepto_30       Strepto_30
BGC4    BGC1    Strepto_30       Strepto_40
BGC4    BGC2    Strepto_50       Strepto_40
BGC4    BGC3    Strepto_40       Strepto_40

Я бы хотел оставьте те, где Family1 и Family2 совпадают, например

Ожидаемый результат

BGC1  | BGC2  | Bacteria1    |   Bacteria2
BGC1    BGC2    Strepto_10       Strepto_10
BGC2    BGC1    Strepto_20       Strepto_20
BGC2    BGC3    Strepto_20       Strepto_20
BGC3    BGC2    Strepto_30       Strepto_30
BGC3    BGC4    Strepto_30       Strepto_30
BGC4    BGC3    Strepto_40       Strepto_40

Ответы [ 2 ]

3 голосов
/ 27 мая 2020

Вы можете подмножество с [, где df$Family1 == df$Family2.

df[df$Family1 == df$Family2,]
#   BGC1 BGC2    Family1    Family2
#1  BGC1 BGC2 Strepto_10 Strepto_10
#4  BGC2 BGC1 Strepto_20 Strepto_20
#5  BGC2 BGC3 Strepto_20 Strepto_20
#8  BGC3 BGC2 Strepto_30 Strepto_30
#9  BGC3 BGC4 Strepto_30 Strepto_30
#12 BGC4 BGC3 Strepto_40 Strepto_40
1 голос
/ 27 мая 2020

Вы можете subset, где Bacteria1 и Bacteria2 равны.

subset(df, Bacteria1 == Bacteria2)

#   BGC1 BGC2  Bacteria1  Bacteria2
#1  BGC1 BGC2 Strepto_10 Strepto_10
#4  BGC2 BGC1 Strepto_20 Strepto_20
#5  BGC2 BGC3 Strepto_20 Strepto_20
#8  BGC3 BGC2 Strepto_30 Strepto_30
#9  BGC3 BGC4 Strepto_30 Strepto_30
#12 BGC4 BGC3 Strepto_40 Strepto_40

Использование dplyr filter.

dplyr::filter(df, Bacteria1 == Bacteria2)
...