Justas Mundeikis
Justas Mundeikis

Reputation: 995

Filtering identical elements with different values in columns

How could I filter the following data frame in R:

NR <- c("AW1","AW1","AW2","AW3","AW3","AW4","AW4")

TYPE <- c("KA","MA","KA2","KA","KA","MA","KA")

df <- data.frame(NR,TYPE)

So I receive and create a new dataframe:

NR  TYPE    
AW1 KA
AW1 MA
AW4 MA
AW4 KA

So the general idea is to find the identical values in first column but only with different values in second column.

Upvotes: 2

Views: 75

Answers (2)

David C.
David C.

Reputation: 1994

You can also use the base package to get the desired data.frame:

df <- df[which(duplicated(df$NR) | duplicated(df$NR, fromLast=TRUE)), ]
df <- df[which(!duplicated(df$TYPE) | !duplicated(df$TYPE, fromLast=TRUE)), ]
df
## NR TYPE
## 1 AW1   KA
## 2 AW1   MA
## 6 AW4   MA
## 7 AW4   KA

Upvotes: 0

salient
salient

Reputation: 2486

Using dplyr:

library(dplyr)

df %>% 
group_by(NR) %>% 
filter(n_distinct(TYPE)>1)

Upvotes: 2

Related Questions