On Apr 10, 2012, at 7:33 PM, Worik R wrote:
Friends
I am extracting sub-sets of the rows of a matrix. Generally the
result is
a matrix. But there is a special case. When the result returned is a
single row it is returned as a vector (in the example below an integer
vector). If there are 0, or more than 1 rows returned the result is a
matrix.
I am doing this in a function and I cannot be sure how many rows I am
removing. How can I do this in a general way that always returns a
matrix?
?"["
> M[1, , drop=FALSE]
a b c d
a1 0 3 2 1
> class( M[1, , drop=FALSE] )
[1] "matrix"
M <- matrix(0:3, nrow=3, ncol=4)
colnames(M) <- c('a','b','c','d')
rownames(M) <- c('a1','b2','c3')
N <- M[M[,"a"]==0,]
O <- M[M[,"a"]!=0,]
P <- M[M[,"a"]==100,]
c(class(M), class(N), class(O), class(P))
[1] "matrix" "integer" "matrix" "matrix"
M
a b c d
a1 0 3 2 1
b2 1 0 3 2
c3 2 1 0 3
N
a b c d
0 3 2 1
O
a b c d
b2 1 0 3 2
c3 2 1 0 3
P
a b c d
cheers
Worik
[[alternative HTML version deleted]]
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
West Hartford, CT
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.