create a loop that brings in matricies from csv files and adds them all together in r

# Create a list to store the matrices
matrices_list <- list()

# Get a list of csv files in the directory
csv_files <- list.files(pattern = "\\.csv$")

# Read each csv file, convert it to a matrix, and store it in the list
for(file in csv_files){
  data <- read.csv(file)
  mat <- as.matrix(data)
  matrices_list[[length(matrices_list) + 1]] <- mat
}

# Initialize a result matrix with zeros
result <- matrix(0, nrow = nrow(matrices_list[[1]]), ncol = ncol(matrices_list[[1]]))

# Loop through each matrix and add it to the result matrix
for(mat in matrices_list){
  result <- result + mat
}

# Display the final result
result
627 chars
24 lines

related categories

gistlibby LogSnag