YouTip LogoYouTip

R Func Names

R names() Function - Name Operations

\\n

Image 3: R Language Examples R Language Examples

\\n

The names() function is used to get or set the name attribute of an object.

\\n

names() can be applied to vectors, lists, and data frames to manage element names.

\\n

The syntax of the names() function is as follows:

\\n
names(x)\\nnames(x) <- value\\n
\\n

Parameter Description:

\\n
    \\n
  • x Input object (vector, list, or data frame).
  • \\n
  • value The name vector to be set.
  • \\n
\\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
\\n

Executing 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

Image 4: R Language Examples R Language Examples

← R Func OrderR Func Merge β†’