Explain Subsetting in R programming?

Subsetting allows the user to access elements from an object. It takes out a portion from the object based on the condition provided. There are 4 ways of subsetting in R programming. Each of the methods depends on the usability of the user and the type of object.

Subsetting in R Using [ ] Operator: Using the ‘[ ]’ operator, elements of vectors and observations from data frames can be accessed. To neglect some indexes, ‘-‘ is used to access all other indexes of vector or data frame.
Subsetting in R Using [[ ]] Operator: [[ ]] operator is used for subsetting of list-objects. This operator is the same as [ ] operator but the only difference is that [[ ]] selects only one element whereas [ ] operator can select more than 1 element in a single command.
Subsetting in R Using $ Operator: $ operator can be used for lists and data frames in R. Unlike [ ] operator, it selects only a single observation at a time. It can be used to access an element in named list or a column in data frame. $ operator is only applicable for recursive objects or list-like objects.
Subsetting in R Using subset() Function: subset() function in R programming is used to create a subset of vectors, matrices, or data frames based on the conditions provided in the parameters.

Following is an example of subsetting using [ ] operator:

# Create vector
x <- 1:15
 
# Print vector
cat("Original vector: ", x, "\n")
 
# Subsetting vector
cat("First 5 values of vector: ", x[1:5], "\n")
 
cat("Without values present at index 1, 2 and 3: ",
                              x[-c(1, 2, 3)], "\n")

Output:

Original vector:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
First 5 values of vector:  1 2 3 4 5
Without values present at index 1, 2 and 3:  4 5 6 7 8 9 10 11 12 13 14 15