Combining column numbers with identical values

I have a matrix as follows

[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] 1 1 3 2 3 1 1 2 3 3 2 

and the next is my desired result (combining column numbers with the same values).

 a<-1,2,6,7 b<-3,5,9,10 c<-4,8,11 
+6
source share
4 answers

The following is a list that should be sufficient:

 aList <- setNames(split(seq_along(mat), mat), unique(letters[mat])) aList # $a # [1] 1 2 6 7 # # $c # [1] 4 8 11 # # $b # [1] 3 5 9 10 

But if you really need variables in your environment, you can:

 attach(aList) 
+5
source
 m1 <- matrix(c(1, 1, 3, 2, 3, 1, 1, 2, 3, 3, 2), nrow = 1) split(seq_len(ncol(m1)), m1[1, ]) 

provides a list with the necessary items. I assume that you really do not want to create vectors a , b and c

 split(seq_len(ncol(m1)), m1[1, ]) $`1` [1] 1 2 6 7 $`2` [1] 4 8 11 $`3` [1] 3 5 9 10 
+1
source

Your question is a little strange, and I suspect you are missing a few details. To get exactly what you want is a little awkward. First create some data:

 ##Some data R> m = matrix(sample(1:3, 10, replace=T), ncol=10) R> m [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 2 2 3 1 3 3 2 2 1 

Then highlight the unique values:

 R> v = unique(m[1,]) 

Now create the vectors you need:

 R> (a = which(v[1]==m[1,])) [1] 1 5 10 R> (b = which(v[2]==m[1,])) [1] 2 3 8 9 R> (c = which(v[3]==m[1,])) [1] 4 6 7 

However, it is not scalable (or elegant). If you have more than a couple of values, you will need to iterate over v , so something like:

 (l = sapply(v, function(i) which(m[1, ] == i))) 

The variable l is a list. To access individual items, use

 l[[1]] l[[2]] l[[3]] 
0
source

You can use by to group duplicate elements and return their growth names.

 tab <- read.table(text ='[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] 1 1 3 2 3 1 1 2 3 3 2',head=T) x <- t(tab) by(x,x,FUN=rownames) INDICES: 1 [1] "X..1." "X..2." "X..6." "X..7." ---------------------------------------------------------------------------------------------------------- INDICES: 2 [1] "X..4." "X..8." "X..11." ---------------------------------------------------------------------------------------------------------- INDICES: 3 [1] "X..3." "X..5." "X..9." "X..10." 

EDIT more beautiful conclusion

 rownames(x) <- 1:nrow(x) > by(x,x,FUN=rownames) INDICES: 1 [1] "1" "2" "6" "7" ---------------------------------------------------------------------------------------------------------- INDICES: 2 [1] "4" "8" "11" ---------------------------------------------------------------------------------------------------------- INDICES: 3 [1] "3" "5" "9" "10" 
0
source

All Articles