[R] Vector extracted from a matrix. How can I specify dimensions in as.matrix?
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Jul 27 16:38:22 CEST 2006
Use the notation x[ , 1, drop = FALSE]
See ?"["
On 7/27/06, Neuro LeSuperHéros <neuro3000 at hotmail.com> wrote:
> 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>
More information about the R-help
mailing list