w3resource

R Programming: Assign new Names to elements of a given List


Write a R program to assign new names "a", "b" and "c" to the elements of a given list.

Sample list: (g1 = 1:10, g2 = "R Programming", g3 = "HTML")

Sample Solution :

R Programming Code :

# Create a list with three elements: a sequence of numbers, a string, and another string
list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")

# Print the original list
print("Original list:")
print(list1)

# Assign new names "one", "two", and "three" to the elements of the list
names(list1) = c("one", "two", "three")

# Print a message about assigning new names to the list elements
print("Assign new names 'one', 'two' and 'three' to the elements of the said list")

# Print the modified list with the new element names
print(list1)

Output:

[1] "Original list:"
$g1
 [1]  1  2  3  4  5  6  7  8  9 10

$g2
[1] "R Programming"

$g3
[1] "HTML"

[1] "Assign new names 'one', 'two' and 'three' to the elements of the said list"
$one
 [1]  1  2  3  4  5  6  7  8  9 10

$two
[1] "R Programming"

$three
[1] "HTML"                         

Explanation:

  • list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")
    • Creates a list named list1 with three elements:
      • g1: a numeric vector from 1 to 10
      • g2: a string "R Programming"
      • g3: a string "HTML"
  • print("Original list:")
    • Prints the message "Original list:" to indicate the original list will be displayed.
  • print(list1)
    • Prints the content of the list list1.
  • names(list1) = c("one", "two", "three")
    • Assigns new names "one", "two", and "three" to the elements of list1, replacing the default names (g1, g2, g3).
  • print("Assign new names 'one', 'two' and 'three' to the elements of the said list")
    • Prints a message explaining that new names have been assigned to the list elements.
  • print(list1)
    • Prints the modified list with the newly assigned names. The elements are now referred to as "one", "two", and "three".

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to add a new item g4 = "Python" to a given list.
Next: Write a R program to get the length of the first two vectors of a given list.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.