How to select unique columns in the R-matrix

I want to select unique columns in a matrix sixfor modeling as follows:

> set.seed(3)
> sam = replicate(100, sample(1:3, 4, rep = T))
> (six = sam[,colSums(sam)==6])
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    2    1    1    1    1    1    1    1    2     1
[2,]    2    2    3    1    1    2    2    1    2     2
[3,]    1    1    1    1    2    1    1    3    1     1
[4,]    1    2    1    3    2    2    2    1    1     2

I would like to get a matrix like:

     [,1] [,2] [,3] [,4] [,5]  [,6] 
[1,]    2    1    1    1    1    1         
[2,]    2    2    3    1    1    1       
[3,]    1    1    1    1    2    3       
[4,]    1    2    1    3    2    1        
+4
source share
2 answers

Use uniquefunction c MARGIN=2, and it will return a matrix with deleted columns; by default, it uniqueremoves duplicate rows:

unique(six, MARGIN = 2)

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    2    1    1    1    1    1
#[2,]    2    2    3    1    1    1
#[3,]    1    1    1    1    2    3
#[4,]    1    2    1    3    2    1
+10
source

We can use duplicated

six[,!duplicated(t(six))]
#    [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    2    1    1    1    1    1
#[2,]    2    2    3    1    1    1
#[3,]    1    1    1    1    2    3
#[4,]    1    2    1    3    2    1
+1
source

Source: https://habr.com/ru/post/1666202/


All Articles