Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know a dimension of matrix or vector in R?

Tags:

r

matlab

I want to find the function in R which does the same as the function size in Matlab.

In Matlab, if A = [ 1 2 3 4 5], then size(A) = 1 5.

If A =[ 1 2 3;4 5 6], then size(A) = 3 3.

In R, I found that the function dim gives the size of a matrix, but it doesn't apply to vectors.

Please help me solve this problem.

Thanks a lot.

like image 708
Jame H Avatar asked Jun 24 '14 10:06

Jame H


People also ask

How do you find the dimensions of a matrix in R?

Get or Set Dimensions of a Matrix in R Programming – dim() Function. dim() function in R Language is used to get or set the dimension of the specified matrix, array or data frame.

How do you know if vector or matrix in R?

matrix() Function. is. matrix() function in R Language is used to return TRUE if the specified data is in the form of matrix else return FALSE.

How do you identify the dimensions of a matrix?

A matrix is a rectangular arrangement of numbers into rows and columns. Each number in a matrix is referred to as a matrix element or entry. The dimensions of a matrix give the number of rows and columns of the matrix in that order. Since matrix A has 2 rows and 3 columns, it is called a 2 × 3 2\times 3 2×3 matrix.

What is the main difference between matrix and vector in R?

A matrix is a rectangular array of numbers while a vector is a mathematical quantity that has magnitude and direction. 2. A vector and a matrix are both represented by a letter with a vector typed in boldface with an arrow above it to distinguish it from real numbers while a matrix is typed in an upper-case letter.


2 Answers

Try dim(A) it's equal to Matlab size(A) function

like image 122
BiXiC Avatar answered Nov 15 '22 10:11

BiXiC


As you noted dim doesn't work on vectors. You can use this function which will take any number of vectors matrices, data.frames or lists and find their dimension or length:

DIM <- function( ... ){
    args <- list(...)
    lapply( args , function(x) { if( is.null( dim(x) ) )
                                    return( length(x) )
                                 dim(x) } )
}

# length 10 vector
a <- 1:10
# 3x3 matrix
b <- matrix(1:9,3,3)
# length 2 list
c <- list( 1:2 , 1:100 )
# 1 row, 2 column data.frame
d <- data.frame( a =1 , b = 2 )


DIM(a,b,c,d)
#[[1]]
#[1] 10

#[[2]]
#[1] 3 3

#[[3]]
#[1] 2

#[[4]]
#[1] 1 2
like image 34
Simon O'Hanlon Avatar answered Nov 15 '22 09:11

Simon O'Hanlon