R colnames() and rownames() Functions - Row and Column Name Operations
The R colnames() function is used to get or set the column names of a matrix/data frame, and rownames() is used for row names.
Setting meaningful names for rows and columns makes code more readable.
The syntax of the colnames() and rownames() functions is as follows:
colnames(x)
colnames(x) <- value
rownames(x)
rownames(x) <- value
Parameter Description:
-
x Input matrix or data frame.
-
value A vector of names to set.
Example
Create a matrix and set row and column names
m
<-
matrix
(
1
:
9
,
nrow
=
3
)
colnames
(
m
)
<-
c
(
"Col A"
,
"Col B"
,
"Col C"
)
rownames
(
m
)
<-
c
(
"Row 1"
,
"Row 2"
,
"Row 3"
)
(
"Matrix with Row and Column Names:"
)
(
m
)
Get row and column names
(
"Column Names:"
)
(
colnames
(
m
)
)
(
"Row Names:"
)
(
rownames
(
m
)
)
Access by row and column names
(
paste
(
"m['Row 2', 'Col C'] ="
, m
[
"Row 2"
,
"Col C"
]
)
)
The output of the code above is:
[1] "带行列名的矩阵:"
列A 列B 列C
行1 1 4 7
行2 2 5 8
行3 3 6 9
[1] "列名:"
[1] "列A" "列B" "列C"
[1] "行名:"
[1] "行1" "行2" "行3"
[1] "m['行2', '列C'] = 8"
R Language Examples