[R] Vector extracted from a matrix. How can I specify dimensions in as.matrix?
Neuro LeSuperHéros
neuro3000 at hotmail.com
Thu Jul 27 15:23:21 CEST 2006
Transpose vector extracted from a matrix
Hello,
I am doing a recursive analysis that uses every line (vector) of a matrix in
a loop. In the model, I need to transpose those vectors that are extracted
from a matrix.
Using simple vectors (no matrix involved) the transpose function works fine:
simplevector <-matrix(1:3,3,1)
tsimplevector <-t(simplevector) #transposed
dim(simplevector) #3x1 matrix (vector)
dim(tsimplevector)#1x3
PROBLEM: However, when the vector is extracted from a matrix, its dimension
is NULL. In this case the transposed dimension is correct, but you'll see
the next example, that if a row was extracted, the dimension would be wrong:
initialmatrix <- matrix(1:9,3,3)
extractedvector <-initialmatrix[,1] # extract first columm as vector
textractedvector <-t(extractedvector)#transposed
dim(extractedvector) #NULL!!!! <- not working
dim(textractedvector)#1x3 as expected
I have tried to transform the extracted vector as.vector and as.matrix.
as.vector does not give the what I want (still NULL) and as.matrix can't
specify the number of row and columns so both vectors are vertical.
In this example, I extract a column and a row. Notice that both
as.matrix(vector) have the same dimension. Notice that both transposed
vectors have 1x3 dimensions.
initialmatrix <- matrix(1:9,3,3)
extractedvector3x1 <-initialmatrix[,1] # extract first columm as vector
extractedvector1x3 <-initialmatrix[1,] # extract first row as vector
#Both are NULL
dim(extractedvector3x1) #NULL!!!!
dim(extractedvector1x3) #NULL!!!!
#transposed dimensions both 1x3
dim(t(extractedvector3x1)) #1x3
dim(t(extractedvector1x3)) #1x3 <- not 3x1
#as.vector: still NULL
dim(as.vector(extractedvector3x1)) #NULL!!!!
dim(as.vector(extractedvector1x3)) #NULL!!!!
#as.matrix: Both dim at 3x1
dim(as.matrix(extractedvector3x1)) #3x1
dim(as.matrix(extractedvector1x3)) #3x1 <- Problem: not 1x3
#as.matrix transposed: Both dim at 1x3
dim(as.matrix(t(extractedvector3x1))) #1x3
dim(as.matrix(t(extractedvector1x3))) #1x3 <- Problem: not 3x1
How can I get correct dimensions? Is there a way to specify dimensions in
as.matrix?
Neuro
More information about the R-help
mailing list