R dim() nrow() ncol() Functions - View Dimensions
R dim() function is used to get or set the dimensions (number of rows and columns) of a matrix/data frame.
nrow() and ncol() are used to get the number of rows and columns separately.
The syntax of these functions is as follows:
dim(x) nrow(x) ncol(x)
Parameter description:
xInput matrix, data frame, or array.
Examples
# Create a matrix
m <- matrix(1:12, nrow = 3, ncol = 4)
print("Matrix:")
print(m)
# View dimensions
print(paste("Dimension dim:", toString(dim(m))))
print(paste("Number of rows nrow:", nrow(m)))
print(paste("Number of columns ncol:", ncol(m)))
# Use dim to modify the matrix shape
vec <- 1:12
dim(vec) <- c(3, 4)
print("Vector becomes a 3x4 matrix:")
print(vec)
m <- matrix(1:12, nrow = 3, ncol = 4)
print("Matrix:")
print(m)
# View dimensions
print(paste("Dimension dim:", toString(dim(m))))
print(paste("Number of rows nrow:", nrow(m)))
print(paste("Number of columns ncol:", ncol(m)))
# Use dim to modify the matrix shape
vec <- 1:12
dim(vec) <- c(3, 4)
print("Vector becomes a 3x4 matrix:")
print(vec)
Executing the above code produces the following output:
[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
Other Extensions
R Language Examples