Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R dim() nrow() ncol() Functions - Viewing Dimensions

R dim() nrow() ncol() Functions - Viewing Dimensions

R Language Examples R Language Examples

The R dim() function is used to get or set the dimensions (number of rows and columns) of a matrix or data frame.

nrow() and ncol() are used to obtain the number of rows and columns separately.

The syntax of these functions is as follows:

dim(x)

nrow(x)

ncol(x)

Parameter Description:

Example

Create a matrix

m

<-

matrix

(

1

:

12

,

nrow

=

3

,

ncol

=

4

)

print

(

"Matrix:"

)

print

(

m

)

View dimensions

print

(

paste

(

"Dimensions dim:"

,

toString

(

dim

(

m

)

)

)

)

print

(

paste

(

"Rows nrow:"

,

nrow

(

m

)

)

)

print

(

paste

(

"Columns ncol:"

,

ncol

(

m

)

)

)

Use dim to change the shape of a matrix

vec

<-

1

:

12

dim

(

vec

)

<-

c

(

3

,

4

)

print

(

"Vector converted to a 3x4 matrix:"

)

print

(

vec

)

The output of the code above is:

[1] "矩阵:"

     [,1] [,2] [,3] [,4]

[1,]    1    4    7   10

[2,]    2    5    8   11

[3,]    3    6    9   12

[1] "维度 dim: 3, 4"

[1] "行数 nrow: 3"

[1] "列数 ncol: 4"

[1] "向量变为 3x4 矩阵:"

     [,1] [,2] [,3] [,4]

[1,]    1    4    7   10

[2,]    2    5    8   11

[3,]    3    6    9   12

R Language Examples R Language Examples