w3resource

R Programming: Extract all elements except the third element


Write a R program to extract all elements except the third element of the first vector 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 numeric vector, and two strings
list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")

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

# Print the first vector (g1) from the list
print("First vector:")
print(list1$g1)

# Remove the third element from the first vector (g1)
print("First vector without third element:")
list1$g1 = list1$g1[-3]

# Print the modified first vector without the third element
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] "First vector:"
 [1]  1  2  3  4  5  6  7  8  9 10
[1] "First vector without third element:"
[1]  1  2  4  5  6  7  8  9 10                         

Explanation:

  • Create a list (list1):
    • The list list1 contains three elements:
      • g1: A numeric vector from 1 to 10.
      • g2: A string "R Programming".
      • g3: A string "HTML".
  • Print the original list:
    • The entire list list1 is printed, showing all elements (the vector and the two strings).
  • Print the first vector (g1):
    • The first element of the list, which is the numeric vector g1, is printed.
  • Remove the third element of the first vector:
    • The third element of the vector g1 is removed using list1$g1[-3].
  • Print the modified first vector:
    • The updated vector, which no longer contains the third element, is printed.

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 10 to each element of the first vector in a given list.
Next: Write a R program to add a new item g4 = "Python" to 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.