evoalgs-r-practise/create_lists.R

58 lines
1.7 KiB
R
Raw Normal View History

2024-04-30 08:03:37 +00:00
# 1. Creating a simple list with mixed types
simple_list <- list(name="John", age=25, scores=c(88, 92, 85))
print("Simple List:")
print(simple_list)
# 2. Creating a list using the list() function with named elements
named_list <- list(firstName="Alice", lastName="Smith", details=list(age=30, profession="Data Scientist"))
print("Named List with Nested List:")
print(named_list)
# 3. Creating a list from vectors
vector1 <- 1:5
vector2 <- seq(10, 50, by=10)
vector_list <- list(vector1, vector2)
print("List from Vectors:")
print(vector_list)
# 4. Modifying a list by adding an element
simple_list$gender <- "male" # Adding a new element
print("Modified List (Added Element):")
print(simple_list)
# 5. Modifying a list by removing an element
simple_list$scores <- NULL # Removing an element
print("Modified List (Removed Element):")
print(simple_list)
# 6. Accessing elements in a list
# Access by element name
print("Accessed Element (Name):")
print(named_list$firstName)
# Access by index
print("Accessed Element (Index):")
print(named_list[[2]])
# 7. Concatenating lists
concatenated_list <- c(simple_list, named_list)
print("Concatenated List:")
print(concatenated_list)
# 8. Using lapply to apply a function to each element of a list
# Here we use the length function to find the length of each element
lengths <- lapply(vector_list, length)
print("Lengths of List Elements:")
print(lengths)
# 9. Creating a list with repeated elements using rep()
repeated_list <- list(rep(list(x = 1:3), 3))
print("List with Repeated Elements:")
print(repeated_list)
# 10. Nested lists
nested_list <- list(
sub_list1 = list(item1 = 1, item2 = 2),
sub_list2 = list(item1 = "a", item2 = "b")
)
print("Nested List:")
print(nested_list)