4

When I try to subset a 1-colum matrix by it's row names the subsetting works but an numeric vector is returned.

can you somehow prevent that behaviour and keep the row names?

M<-as.matrix(rnorm(5))
rownames(M)<-LETTERS[1:5]
M
        [,1]
A  0.6250957
B  0.7330598
C -0.7127075
D  0.2162602
E  0.2223444

M <- M[which(rownames(M) != "A")]

M
## [1]  0.7330598 -0.7127075  0.2162602  0.2223444
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Latrunculia
  • 696
  • 1
  • 7
  • 15
  • 2
    You have to add drop=FALSE, as your matrix is one column. `M[which(rownames(M) != "A"),,drop=FALSE]` – akrun Feb 03 '15 at 08:44

1 Answers1

6

you can read about argument drop in the help page: ?'['

M[which(rownames(M) != "A"), ,drop=FALSE]
RockScience
  • 17,932
  • 26
  • 89
  • 125
  • Oh, ok, I didn't know you could use drop=FALSE within the square brackets. I saw the question Henrik referred to, but I didn't see how you could add the drop argument to the subsetting, that's why I asked a new question. Thanks for the quick answer! One more thing: I use the matrix in vegdist( ) with na.rm=TRUE which internally seems to convert it back to a vector (while removing NAs) and then complains that it's a vector. Any thoughts about that? – Latrunculia Feb 03 '15 at 09:00
  • Ok, sorry just saw the other question again, and yes my original question is a full duplicate, sorry. Any thoughts about vegdist though? It's a distance function form the vegan package but I guess the same behaviour may arise with other functions that have a na.rm argument... – Latrunculia Feb 03 '15 at 09:13
  • @user1183277 check the code of `vegdist`. I can also do it for you but what's the point? – RockScience Feb 03 '15 at 10:02