R colnames() and rownames() functions - row and column name operations

R 语言实例R language examples

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 can make code more readable.

The syntax format of colnames() and rownames() functions is as follows:

colnames(x)
colnames(x) <- value
rownames(x)
rownames(x) <- value

Parameter description:

  • xInput matrix or data frame.

  • valueThe name vector to be set.

Examples

# Create matrix and set row and column names
m <- matrix(1:9, nrow = 3)
colnames(m) <- c("Column A", "Column B", "Column 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', 'Column C'] =", m["Row 2", "Column C"]))

Executing the above code produces the following output:

[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 语言实例R language examples

Other extensions