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

R colnames() and rownames() Functions - Row and Column Name Operations

R colnames() and rownames() Functions - Row and Column Name Operations

R Language Examples R Language Examples

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:

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"

)

print

(

"Matrix with Row and Column Names:"

)

print

(

m

)

Get row and column names

print

(

"Column Names:"

)

print

(

colnames

(

m

)

)

print

(

"Row Names:"

)

print

(

rownames

(

m

)

)

Access by row and column names

print

(

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 R Language Examples