[R] behaviour of rows and colomns suppression in a matrix

Olivier ETERRADOSSI olivier.eterradossi at mines-ales.fr
Thu Mar 13 15:02:24 CET 2014


Hi  List,
while running a script on a set of matrices I came into a case I would not
have guessed to arrive.
Below is  a small toy example to illustrate the case.
Of course there is a simple workaround (using a simple test), but why does
this occur, and shouldn’t it be corrected ?

More probably I miss a point, but which one ? Is this behavior obtained on
purpose and why ?
Sorry if it’s a FAQ
 I didn’t find my way to it.
(And sorry for multiple posting if any : I got a warning from r-bounce but
did not understand it).
Thanks, Olivier


#############################################
# toy example 1 (no problem with this one)

toy.matrix.1<-matrix(c(1,0,1,1,0,1,0,0,0),3,3)
# getting the marginal sums
margin.Rows<- apply(toy.matrix.1,MARGIN=1,FUN=sum)
margin.Cols<- apply(toy.matrix.1,MARGIN=2,FUN=sum)
#giving a threshold for lines and columns suppression
thresh<-0
# finding the items to remove
unused.rows<-which(margin.Rows<=thresh)    # unused.rows == 2
unused.cols<-which(margin.Cols<=thresh)        # unused.cols == 3
TM1<-toy.matrix.1
TM1<-TM1[-unused.rows,]
TM1<-TM1[,-unused.cols]
TM1
#     [,1] [,2]
#[1,]    1    1
#[2,]    1    1                         # OK
##############################################

# toy example 2 (oops, no rows to suppress
)

toy.matrix.2<-matrix(c(1,1,1,1,1,1,0,0,0),3,3)
# getting the marginal sums
margin.Rows<- apply(toy.matrix.2,MARGIN=1,FUN=sum)
margin.Cols<- apply(toy.matrix.2,MARGIN=2,FUN=sum)
#giving a threshold for lines and columns suppression
thresh<-0
unused.rows<-which(margin.Rows<=thresh)         # unused.rows ==
integer(0)
unused.cols<-which(margin.Cols<=thresh)              # unused.cols == 3
TM2<-toy.matrix.2
TM2<-TM2[-unused.rows,]
TM2<-TM2[,-unused.cols]
TM2
#      [,1] [,2]                    # empty...
###############################################
# I was expecting :
#     [,1] [,2]
#[1,]    1    1
#[2,]    1    1
#[3,]    1    1

# which of course is obtained using :
TM2<-toy.matrix.2
if(length(unused.rows) !=0) {TM2<-TM2[-unused.rows,]}
if(length(unused.rows) !=0 ){TM2<-TM2[,-unused.cols]}
TM2



More information about the R-help mailing list