Reduce in R

Find this useful? Support us: Star on GitHub 6
Category: Array | Language: R

In R, you can reduce an array to a single value by applying different mathematical operations to the array elements. Here are a few examples:

1. Summing up array elements: To reduce an array to a single value by summing up all the elements, you can use the sum() function.

# Create an array
arr <- c(1, 2, 3, 4)

# Reduce the array to a single value by adding all the elements
result <- sum(arr)
print(result)

Output:
[1] 10

2. Finding the maximum value: To reduce an array to a single value by finding the maximum element, you can use the max() function.

# Create an array
arr <- c(1, 7, 4, 5, 3, 8, 2)

# Reduce the array to a single value by finding the maximum element
result <- max(arr)
print(result)

Output:
[1] 8

3. Finding the minimum value: To reduce an array to a single value by finding the minimum element, you can use the min() function.

# Create an array
arr <- c(1, 7, 4, 5, 3, 8, 2)

# Reduce the array to a single value by finding the minimum element
result <- min(arr)
print(result)

Output:
[1] 1

4. Finding the product of all elements: To reduce an array to a single value by multiplying all the elements, you can use the prod() function.

# Create an array
arr <- c(1, 2, 3, 4)

# Reduce the array to a single value by multiplying all the elements
result <- prod(arr)
print(result)

Output:
[1] 24

These are just a few examples of how to reduce an array to a single value in R. There are many other functions and operations you can use depending on your specific needs.