I have a matrix in the following form
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
1 1 3 2 3 1 1 2 3 3 2
and following is my desired output (combining the column numbers, having same values).
a<-1,2,6,7
b<-3,5,9,10
c<-4,8,11
The following gives you a list which should be enough:
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 then do:
attach(aList)
m1 <- matrix(c(1, 1, 3, 2, 3, 1, 1, 2, 3, 3, 2), nrow = 1)
split(seq_len(ncol(m1)), m1[1, ])
gives you a list with the desired elements. I assume you don't really 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With