find the average of all elements in an array in r

To find the average of all elements in an array in R, you can use a loop to iterate through each element, accumulate the sum, and then divide by the total number of elements. Alternatively, you can use the built-in mean() function, which calculates the arithmetic mean of a numeric vector or array.

Here's an example of how to find the average of an array using both methods:

main.r
# Create a sample array of numbers
my_array <- array(data = c(1, 2, 3, 4, 5), dim = c(1, 5))  # 1 row, 5 columns

# Method 1: Use a loop to calculate the sum
num_elements <- length(my_array)
sum_elements <- 0
for (i in 1:num_elements) {
  sum_elements <- sum_elements + my_array[1, i]
}
avg_elements <- sum_elements / num_elements

# Method 2: Use the built-in mean() function
avg_elements <- mean(my_array)

# Display the average
cat("The average of the array is:", avg_elements)
481 chars
17 lines

This code will output:

main.r
The average of the array is: 3
31 chars
2 lines

gistlibby LogSnag