R dim() nrow() ncol() Functions - Viewing Dimensions
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:
-
x Input matrix, data frame, or array.
Example
Create a matrix
m
<-
matrix
(
1
:
12
,
nrow
=
3
,
ncol
=
4
)
(
"Matrix:"
)
(
m
)
View dimensions
(
paste
(
"Dimensions dim:"
,
toString
(
dim
(
m
)
)
)
)
(
paste
(
"Rows nrow:"
,
nrow
(
m
)
)
)
(
paste
(
"Columns ncol:"
,
ncol
(
m
)
)
)
Use dim to change the shape of a matrix
vec
<-
1
:
12
dim
(
vec
)
<-
c
(
3
,
4
)
(
"Vector converted to a 3x4 matrix:"
)
(
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