find the sum of all elements in an array in r

To find the sum of all elements in an array in R, you can use the sum() function with the array as an argument. Here's an example:

main.r
my_array <- c(1, 2, 3, 4, 5)
array_sum <- sum(my_array)
cat("The sum of the array is:", array_sum)
99 chars
4 lines

Output:

main.r
The sum of the array is: 15
28 chars
2 lines

Alternatively, if you have a multi-dimensional array, you can use a loop to iterate over each element and calculate the sum:

main.r
my_array <- array(1:12, dim = c(3, 4))
array_sum <- 0

for (i in 1:dim(my_array)[1]) {
  for (j in 1:dim(my_array)[2]) {
    array_sum <- array_sum + my_array[i, j]
  }
}

cat("The sum of the array is:", array_sum)
215 chars
11 lines

Output:

main.r
The sum of the array is: 78
28 chars
2 lines

related categories

gistlibby LogSnag