To initialize a set in R, you can use the set() function with or without initial elements.
In this example,
set()
function to create a set in R with initial elements.set()
function to initialize the set with these elements.# Initialize a set with elements
my_set <- set(c("apple", "banana", "orange"))
# my_set is now initialized with elements "apple", "banana", and "orange"
# Example usage:
# Add elements to the set
my_set <- union(my_set, c("kiwi"))
# Remove elements from the set
my_set <- setdiff(my_set, c("banana"))
# Check if an element is present in the set
contains_element <- "apple" %in% my_set
print(paste("Is element 'apple' present in the set:", contains_element))
Is element 'apple' present in the set: TRUE
In this example,
set()
function without passing any arguments to create an empty set in R.# Initialize an empty set
empty_set <- set()
# empty_set is now initialized as an empty set
# Example usage:
# Add elements to the set
empty_set <- union(empty_set, c("apple"))
# Remove elements from the set
empty_set <- setdiff(empty_set, c("apple"))
# Check if an element is present in the set
contains_element <- "apple" %in% empty_set
print(paste("Is element 'apple' present in the set:", contains_element))
Is element 'apple' present in the set: FALSE
In this tutorial, we learned How to Initialize a Set in R language with well detailed examples.