Home > front end >  How to treat a single row of matrix in R as a matrix object
How to treat a single row of matrix in R as a matrix object

Time:03-25

I have an R script that removes random rows from an nxm (n row, m column) matrix depending on which elements occur in a data set. I have a conditional statement that terminates if there are no rows remaining. This works fine if there are 0 rows, but not if there is one.

For example, if I have

m1 = rbind(c(1,2),c(1,4),c(2,3),c(2,4))

and I delete all rows

m1 = m1[-c(1,2,3,4),]

the conditional statement

if(length(m1[,1]) > 0)

evaluates correctly to FALSE and the program terminates, since the object m1 is a 0x2 matrix. However, if I delete all but one row, e.g.

m1 = m1[-c(1,2,4),]

the same conditional statement does not evaluate because the remaining row is no longer treated as a matrix object of dimension 1xn, but rather as a numeric vector, so dim, length(m[,1]) etc are undefined.

Is there some way to preserve a single row as a 1xn matrix object, other than checking if only a single row remains and applying t(as.matrix(m1)), which would be a very clumsy approach?

I've appended my complete script below, but the details of the script shouldn't be necessary to address this question. The while(temp_mat[,1] > 0) is the step that breaks if I have a single row (but works fine if there are none or any number of rows > 1)

seq_to_mask = function(mat){
temp_mat = mat
to_mask = c()
iter = 0
while(length(temp_mat[,1])>0){
    all_instances = c(temp_mat[,1],temp_mat[,2])
    #number of times a sample appears
    occurrences = sort(table(all_instances))
    max_instances = as.numeric(names(occurrences)[length(occurrences)])
    posits = which(temp_mat[,1]==max_instances | temp_mat[,2]==max_instances)
    to_mask = c(to_mask, max_instances)
    temp_mat = temp_mat[-posits,]
    iter = iter   1
}
return(to_mask)
}

CodePudding user response:

The reason seems to be the coercion of matrix to vector when there is a single row/column. We can use drop = FALSE (by default it is drop = TRUE)

m1 <- m1[-c(1, 2, 4), , drop = FALSE]
  •  Tags:  
  • r
  • Related