evoalgs-r-practise/lists_and_vectors.R
2024-04-30 10:03:37 +02:00

80 lines
2.0 KiB
R

# Vectors
# -------
# Creating a numeric vector
numeric_vector <- c(1, 2, 3, 4, 5)
print("Numeric Vector:")
print(numeric_vector)
# Creating a character vector
character_vector <- c("apple", "banana", "cherry")
print("Character Vector:")
print(character_vector)
# Accessing elements in a vector
print("Element at index 2 of Numeric Vector:")
print(numeric_vector[2])
# Modifying elements in a vector
numeric_vector[2] <- 10
print("Modified Numeric Vector:")
print(numeric_vector)
# Lists
# -----
# Creating a simple list
simple_list <- list(name="John", age=25, scores=c(88, 92, 85))
print("Simple List:")
print(simple_list)
# Accessing elements in a list by name
print("Name from List:")
print(simple_list$name)
# Accessing elements in a list by index
print("Scores from List:")
print(simple_list[[3]])
# Modifying elements in a list
simple_list$age <- 26
print("Modified List:")
print(simple_list)
# Differences between Lists and Vectors
# -------------------------------------
# Lists can contain elements of different types
mixed_list <- list(number=42, text="hello", vector=c(1, 2, 3))
print("Mixed Type List:")
print(mixed_list)
# Vectors must have elements of the same type
# Attempting to mix types will coerce to the most flexible type
mixed_vector <- c(1, "two", TRUE)
print("Mixed Type Vector (coerced):")
print(mixed_vector)
# Matrices
# --------
# Creating a matrix
matrix_example <- matrix(1:9, nrow = 3, ncol = 3)
print("Matrix Example:")
print(matrix_example)
# Accessing elements in a matrix
print("Element at row 2, column 3:")
print(matrix_example[2, 3])
# Modifying elements in a matrix
matrix_example[1, 2] <- 10
print("Modified Matrix:")
print(matrix_example)
# Creating a matrix with named columns
named_matrix <- matrix(1:9, nrow = 3, ncol = 3, dimnames = list(NULL, c("col1", "col2", "col3")))
print("Matrix with Named Columns:")
print(named_matrix)
# Accessing elements in a matrix with named columns using $ indexing
print("Element in 'col2':")
print(named_matrix[, "col2"])