如何知道R中矩阵或向量的维数? [英] How to know a dimension of matrix or vector in R?

查看:1272
本文介绍了如何知道R中矩阵或向量的维数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中找到与Matlab中的函数size相同的函数.

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

在Matlab中,如果A = [ 1 2 3 4 5],则为size(A) = 1 5.

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

如果为A =[ 1 2 3;4 5 6],则为size(A) = 3 3.

在R中,我发现函数dim给出了矩阵的大小,但不适用于向量.

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.

非常感谢.

推荐答案

如前所述,dim在矢量上不起作用.您可以使用此函数,该函数将获取任意数量的向量矩阵,data.frames或列表,并找到它们的dimensionlength:

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

这篇关于如何知道R中矩阵或向量的维数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆