colnames()

colnames(x) <- value
Returns: character vector or NULL · Updated March 13, 2026 · Base Functions
vectors dimensions base

colnames() retrieves or sets the column names of matrices, data frames, and array-like objects. They are essential for working with tabular data and are the column equivalent of rownames() for rows.

Syntax

# Get column names
colnames(x)

# Set column names
colnames(x) <- value

Parameters

ParameterTypeDefaultDescription
xmatrix, data.frame, or arrayThe object whose column names to get or set
valuecharacter vector or NULLNew column names to assign

Examples

Basic usage

df <- data.frame(
  name = c("Alice", "Bob", "Carol"),
  age = c(25, 30, 35),
  score = c(85, 92, 78)
)

colnames(df)
# [1] "name"  "age"   "score"

Setting column names

colnames(df) <- c("Name", "Age", "Score")
df
#   Name Age Score
# 1 Alice  25     85
# 2   Bob  30     92
# 3 Carol  35     78

Working with matrices

mat <- matrix(1:9, nrow = 3, ncol = 3)
colnames(mat) <- c("A", "B", "C")
mat
#   A B C
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9

Common Patterns

Subset by column name:

df[, "age"]
# [1] 25 30 35

Check if column exists:

"score" %in% colnames(df)
# [1] TRUE

Rename specific columns:

colnames(df)[colnames(df) == "score"] <- "final_score"

See Also