Home > Back-end >  Creating a function that calculates the min and max without using min() | max()
Creating a function that calculates the min and max without using min() | max()

Time:07-10

I am trying to create a function which returns the min & max value of a vector.

Currently I have created 2 seperate functions but I need the one to return similar output like so. min max -2.078793 2.041260

Vector

vec <- rnorm(20)

Functions

minmax <- function(x) {
  my_min = Inf
  for (i in seq_along(x)) {
    if (x[i] < my_min) my_min = x[i]
  }
  return(min = my_min)
}


minmax <- function(x) {
  my_max = 0
  for (i in seq_along(x)) {
    if (x[i] > my_max) my_max = x[i]
  }
  return(max = my_max)
}

CodePudding user response:

Consider head() or tail() after sorting:

minmax <- function(x) {
    sorted_vec <- sort(x)
    c(min=head(sorted_vec, 1), max=tail(sorted_vec, 1))
}

Alternatively, by indexing after sorting:

minmax <- function(x) {
  sorted_vec <- sort(x)
  c(min=sorted_vec[1], max=sorted_vec[length(x)])
}

CodePudding user response:

Try this function

minmax <- function(x) {
    my_min = Inf 
    my_max = - Inf
    for (i in seq_along(x)) {
        if (x[i] < my_min) my_min = x[i]
        if (x[i] > my_max) my_max = x[i]
    }
    cat("min , max :" , my_min , " , " , my_max)
}
  • Related