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

54 lines
1.5 KiB
R

# Creating a matrix for demonstration
matrix_data <- matrix(1:9, nrow=3, byrow=TRUE)
print("Original Matrix:")
print(matrix_data)
# Using apply on a matrix
# -----------------------
# Sum of each row
row_sums <- apply(matrix_data, 1, sum)
print("Sum of each row:")
print(row_sums)
# Sum of each column
col_sums <- apply(matrix_data, 2, sum)
print("Sum of each column:")
print(col_sums)
# Creating a list for demonstration
list_data <- list(a = 1:5, b = 6:10, c = 11:15)
print("Original List:")
print(list_data)
# Using lapply on a list
# ----------------------
# Compute the mean of each element in the list
list_means <- lapply(list_data, mean)
print("Mean of each list element:")
print(list_means)
# Using sapply on a list
# ----------------------
# sapply simplifies the result to a vector or matrix if possible
list_means_simplified <- sapply(list_data, mean)
print("Simplified mean of each list element:")
print(list_means_simplified)
# Using vapply on a list
# ----------------------
# vapply allows for specifying the type of return value, making it safer than sapply
list_means_vapply <- vapply(list_data, mean, numeric(1))
print("Vapply mean of each list element:")
print(list_means_vapply)
# Creating a vector and factor for demonstration
vector_data <- c(1, 2, 3, 4, 5, 6)
factor_data <- gl(2, 3, labels = c("Group1", "Group2"))
# Using tapply on a vector
# ------------------------
# Apply a function over subsets of a vector
group_means <- tapply(vector_data, factor_data, mean)
print("Mean of vector elements by group:")
print(group_means)