2

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)
Brotkrumen
  • 59
  • 3

1 Answers1

4

Try

testm <- testm[-1,,drop=FALSE]   
lebatsnok
  • 6,329
  • 2
  • 21
  • 22
  • Even says so in the documentation for '['. never thought to look there. thanks! – Brotkrumen Jun 17 '18 at 19:29
  • Thanks. Never would have thought of that in a 1000 years! (Link to the [docs](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/Extract)) – daviewales Jun 15 '22 at 05:59