R names() Function - Name Operations
\\n\\nThe names() function is used to get or set the name attribute of an object.
\\nnames() can be applied to vectors, lists, and data frames to manage element names.
\\nThe syntax of the names() function is as follows:
\\nnames(x)\\nnames(x) <- value\\n\\nParameter Description:
\\n- \\n
- x Input object (vector, list, or data frame). \\n
- value The name vector to be set. \\n
Example
\\n# Set names for vector elements\\nscores <- c(88, 92, 76, 85, 90)\\nnames(scores) <- c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "Qian Qi")\\nprint("Named vector:")\\nprint(scores)\\n\\n# Access elements by name\\nprint(paste("Li Si's score:", scores))\\n\\n# Get and modify data frame column names\\ndf <- data.frame(a = 1:3, b = 4:6)\\nprint("Column names before modification:")\\nprint(names(df))\\nnames(df) <- c("Column 1", "Column 2")\\nprint("Column names after modification:")\\nprint(names(df))\\n\\nExecuting the above code outputs:
\\n "Named vector:"\\n Zhang San Li Si Wang Wu Zhao Liu Qian Qi \\n 88 92 76 85 90 \\n "Li Si's score: 92"\\n "Column names before modification:"\\n "a" "b"\\n "Column names after modification:"\\n "Column 1" "Column 2"\\n\\n
YouTip
R Language Examples