[R] Extract pairs (rowname, columname) from a matrix where value is 0

Gabor Grothendieck ggrothendieck at gmail.com
Thu Jul 16 07:03:35 CEST 2009


Here is a variation on the solution below (first line
is the same but second differs):

> ind <- which(a == 0, arr = TRUE)
> mapply("[", dimnames(a), as.data.frame(ind))
     [,1] [,2]
[1,] "A1" "F1"
[2,] "A3" "F1"
[3,] "A2" "F2"
[4,] "A3" "F3"


On Thu, Jul 16, 2009 at 12:40 AM, Jorge Ivan
Velez<jorgeivanvelez at gmail.com> wrote:
> Dear Alberto,
> Try this:
>
> # colnames and rownames
> cn <- colnames(a)
> rn <- rownames(a)
>
> # the index
> ind <- which(a==0, arr = TRUE)
>
> # the result
> data.frame( res = apply(ind, 1, function(x)
>                        paste(rn[x[1]],",", cn[x[2]], sep ="")
>                                      )
>            )
>
> #   res
> # 1 A1,F1
> # 2 A3,F1
> # 3 A2,F2
> # 4 A3,F3
>
> See ?which, ?apply and ?paste for more information.
>
> HTH,
>
> Jorge
>
>
> On Wed, Jul 15, 2009 at 7:15 PM, Alberto Lora M <albertoloram at gmail.com>wrote:
>
>> Dear sir,
>>
>> I have a matrix like
>>
>> a<-matrix(c(0,2,0,4,0,6,5,8,0),nrow=3)
>> colnames(a)<-c("F1","F2","F3")
>> rownames(a)<-c("A1","A2","A3")
>> a
>>
>>   F1 F2 F3
>> A1  0  4  5
>> A2  2  0  8
>> A3  0  6  0
>>
>> I want to extract all pairs (rownames, columnames) from which the value in
>> the matrix is 0
>>
>> The result should be something like this
>>
>> A1, F1
>> A2, F2
>> A3, F1
>> A3, F3
>>
>> how it is possible?
>>
>> thanks for your help....
>>
>> Best Regards
>>
>> Alberto
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list