Search code examples
rdataframeunique

R: Extract unique values in columns of a dataframe


I have a dataframe in R and I wonder if it is possible to retrieve values of a column that are not present in the others columns and this for each column.

My dataframe looks like :

sample_1 sample_2 sample_3
   a        a        a       
   c        e        c
   d        f        e
   g        m        j
   m        n        n
   x        u        w
   t        z        z

I would like to get the following result:

sample_1 sample_2 sample_3
   d        f        j
   g        u        w
   x
   t

Thank you in advance for your answers,


Solution

  • You can try

    lst <- lapply(seq_along(df1), function(i) df1[,i][!df1[,i] %in%
                          unique(unlist(df1[-i]))])
     library(stringi)
     as.data.frame(stri_list2matrix(lst, fill=''))