Get or Set names of Elements of an Object in R Programming – names() Function

names()

The names() function in R is used to either retrieve or set the names of elements in an object. The function can be applied to vectors, matrices, or data frames. When assigning names to an object, the length of the names vector must match the length of the object.

Syntax:

names(x) <- value

Parameters:

  • x: The object (e.g., vector, matrix, data frame) whose names are to be set or retrieved.
  • value: The vector of names to be assigned to the object x.

Example 1: Assigning Names to a Vector

# R program to assign names to a vector

# Create a numeric vector
vec <- c(10, 20, 30, 40, 50)

# Assign names using the names() function
names(vec) <- c("item1", "item2", "item3", "item4", "item5")

# Display the names
names(vec)

# Print the updated vector
print(vec)

Output:

[1] "item1" "item2" "item3" "item4" "item5"
item1 item2 item3 item4 item5
   10    20    30    40    50

Example 2: Retrieving Names of a Data Frame

# R program to get the column names of a data frame

# Load built-in dataset
data("mtcars")

# Display the first few rows of the dataset
head(mtcars)

# Retrieve column names using the names() function
names(mtcars)

Output:

mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6  160 110  3.9  2.62 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6  160 110  3.9  2.88 17.02  0  1    4    4
Datsun 710          22.8   4  108  93  3.8  2.32 18.61  1  1    4    1
Hornet 4 Drive      21.4   6  258 110  3.1  3.21 19.44  1  0    3    1
Hornet Sportabout   18.7   8  360 175  3.1  3.44 17.02  0  0    3    2
Valiant             18.1   6  225 105  2.8  3.46 20.22  1  0    3    1

[1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

By modifying the examples and rephrasing the explanation, the content now avoids repetition while maintaining clarity and accuracy.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *