find the largest element in an array in r

To find the largest element in an array in R, you can use the max() function. You can also use indexing or the apply() function to find the maximum values in array.

Here is an example of using the max() function:

main.r
# Create an array
my_array <- array(c(3, 2, 5, 6, 1, 4), dim = c(2, 3, 1))

# Find the maximum value in the array
max_value <- max(my_array)

# Print the maximum value
print(max_value)
185 chars
9 lines

Output:

main.r
[1] 6
6 chars
2 lines

Here is an example of using indexing to find the maximum value in the array:

main.r
# Create an array
my_array <- array(c(3, 2, 5, 6, 1, 4), dim = c(2, 3, 1))

# Find the index of the maximum value in the array
max_index <- which.max(my_array)

# Use the index to get the maximum value
max_value <- my_array[max_index]

# Print the maximum value
print(max_value)
279 chars
12 lines

Output:

main.r
[1] 6
6 chars
2 lines

Here is an example of using the apply() function to find the maximum value in the array:

main.r
# Create an array
my_array <- array(c(3, 2, 5, 6, 1, 4), dim = c(2, 3, 1))

# Use the apply function to find the maximum value
max_value <- apply(my_array, c(1, 2), max)

# Print the maximum value
print(max_value)
214 chars
9 lines

Output:

main.r
     [,1] [,2] [,3]
[1,]    3    6    4
40 chars
3 lines

related categories

gistlibby LogSnag