w3resource

R Programming: Add a new item g4 = "Python" to a given list

R Programming: List Exercise-18 with Solution

Write a R program to add a new item g4 = "Python" to a given list.

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

Sample Solution :

R Programming Code :

# Create a list with three items: g1, g2, and g3
list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")

# Print a message indicating the original list
print("Original list:")

# Display the original list
print(list1)

# Print a message indicating a new vector will be added to the list
print("Add a new vector to the said list:")

# Add a new item 'g4' to the list, assigning it the value "Python"
list1$g4 = "Python"

# Print the updated list with the new item
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] "Add a new vector to the said list:"
$g1
 [1]  1  2  3  4  5  6  7  8  9 10

$g2
[1] "R Programming"

$g3
[1] "HTML"

$g4
[1] "Python"
                         

Explanation:

  • Creation of a List:
    • list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")
    • A list named list1 is created with three elements:
      • g1 is a vector containing numbers from 1 to 10.
      • g2 is a string "R Programming".
      • g3 is a string "HTML".
  • Print Original List:
    • print("Original list:")
    • Prints the message "Original list:" to indicate the list before any modifications.
  • Display Original List:
    • print(list1)
    • Outputs the content of list1, showing its original elements.
  • Print Addition Message:
    • print("Add a new vector to the said list:")
    • Prints a message indicating that a new item is going to be added to the list.
  • Add a New Item to the List:
    • list1$g4 = "Python"
    • Adds a new item g4 with the value "Python" to the list1.
  • Print Updated List:
    • print(list1)
    • Displays the updated list1 including the newly added g4 item.

R Programming Code Editor:



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

Previous: Write a R program to extract all elements except the third element of the first vector of a given list.
Next: Write a R program to assign new names "a", "b" and "c" to the elements of a given list.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/list/r-programming-list-exercise-18.php