w3resource

R Programming - Add 10 to each element of the first Vector in a List


Write a R program to Add 10 to each element of the first vector in a given list.

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

Sample Solution :

R Programming Code :

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

# Print the message "Original list:"
print("Original list:")

# Print the entire content of list1
print(list1)

# Print the message "New list:"
print("New list:")

# Add 10 to each element of the vector stored in list1$g1
list1$g1 = list1$g1 + 10

# Print the updated vector from list1$g1
print(list1$g1)

Output:

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

$g2
[1] "R Programming"

$g3
[1] "HTML"

[1] "New list:"
 [1] 11 12 13 14 15 16 17 18 19 20                         

Explanation:

  • Create a List:
    • list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")
      • Creates a list named list1 with three elements:
      • g1: a vector of integers from 1 to 10
      • g2: a string "R Programming"
      • g3: a string "HTML"
  • Print Original List:
    • print("Original list:")
      • Prints the text "Original list:" to indicate the following output.
    • print(list1)
      • Prints the entire list1 list.
  • Update and Print Modified List:
    • print("New list:")
      • Prints the text "New list:" to indicate the following output.
    • list1$g1 = list1$g1 + 10
      • Adds 10 to each element of the vector g1 in the list list1.
    • print(list1$g1)
      • Prints the updated vector from list1$g1 after adding 10 to each element.

R Programming Code Editor:



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

Previous: Write a R program to create a list named s containing sequence of 15 capital letters, starting from ‘E’.
Next: Write a R program to extract all elements except the third element of the first vector 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.