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.
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.
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.
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.
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.
Try dim(A)
it's equal to Matlab size(A) function
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With