Remove rows in a dataframe having at least two duplicate columns

Viewed 37

I have the following dataframe:

df=data.frame(word1 = c("Hello", "ah", "why"), word2 = c("dress", "ah", "ahi"), 
              word3 = c("english", "ah", "ahi"), x = c(1L,6L, 1L))

> df
  word1 word2   word3 x
1 Hello dress english 1
2    ah    ah      ah 6
3   why   ahi     ahi 1

I would like to delete the rows that have at least two columns word1, word2, word3 equal with each other.

For instance, the desired result in our example is:

> df
  word1 word2   word3 x
1 Hello dress english 1
3 Answers

A couple options with apply:

cols = c("word1", "word2", "word3")
df[!apply(df[cols], 1, anyDuplicated), ]
#   word1 word2   word3 x
# 1 Hello dress english 1

df[apply(df[cols], 1, function(x) length(unique(x)) == length(x)), ]
#   word1 word2   word3 x
# 1 Hello dress english 1

Using dplyr:

library(dplyr)
df %>%
  filter(word1 != word2 & word1 != word3 & word2 != word3)

I'm working on a more compact way to write the three differences.

If there are three columns, you may also do rowwise filter in dplyr

df %>% rowwise() %>%
  filter(length(unique(c(word1, word2, word3))) == 3)

# A tibble: 1 x 4
# Rowwise: 
  word1 word2 word3       x
  <chr> <chr> <chr>   <int>
1 Hello dress english     1
Related