R names() Function - Name Operations
The R names() function is used to get or set the name attribute of an object.
names() can be applied to vectors, lists, and data frames to manage the names of elements.
The syntax of the names() function is as follows:
names(x) names(x) <- value
Parameter description:
xInput object (vector, list, or data frame).
valueThe name vector to be set.
Example
# Set names for vector elements
scores <- c(88, 92, 76, 85, 90)
names(scores) <- c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi")
print("Vector with names:")
print(scores)
# Access elements by name
print(paste("Li Si's score:", scores["Li Si"]))
# Get and modify data frame column names
df <- data.frame(a = 1:3, b = 4:6)
print("Column names before modification:")
print(names(df))
names(df) <- c("Column1", "Column2")
print("Column names after modification:")
print(names(df))
scores <- c(88, 92, 76, 85, 90)
names(scores) <- c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi")
print("Vector with names:")
print(scores)
# Access elements by name
print(paste("Li Si's score:", scores["Li Si"]))
# Get and modify data frame column names
df <- data.frame(a = 1:3, b = 4:6)
print("Column names before modification:")
print(names(df))
names(df) <- c("Column1", "Column2")
print("Column names after modification:")
print(names(df))
The output after running the above code is:
[1] "带名称的向量:" 张三 李四 王五 赵六 钱七 88 92 76 85 90 [1] "李四的成绩: 92" [1] "修改前列名:" [1] "a" "b" [1] "修改后列名:" [1] "列一" "列二"Other Extensions
R Language Examples