Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent R from downgrading a matrix to a vector [duplicate]

Tags:

r

matrix

Need to reduce a matrix until it has only one element left. That is working fine until I have a 2x2 matrix. When I remove a row or a column from a 2x2 matrix, instead of getting a 1x2 or 2x1 matrix, I end up with a vector and my code blows up.

Testcase:

# 2x2 matrix. remove row and column to get 1x1 matrix
testm <- matrix( data=0, nrow=2, ncol=2, dimnames=list(c("A","B"),c("A","B")))
print(testm)
print(is.matrix(testm))  # TRUE
testm <- testm[-1,]      # should result in 1x2 matrix
print(testm)             # vector
print(is.matrix(testm))  # FALSE
testm <- testm[,-1]      # error
print(testm)
like image 433
Brotkrumen Avatar asked Oct 19 '25 04:10

Brotkrumen


1 Answers

Try

testm <- testm[-1,,drop=FALSE]   
like image 122
lebatsnok Avatar answered Oct 21 '25 17:10

lebatsnok