Home > Enterprise >  Understanding a function
Understanding a function

Time:10-13

I have this function I've been able to do but I don't fully understand the code, as everything is new to me. Would be very helpful if anyone could correct me.

Here is what i think it does:

  • give the function the name find_maximum

  • maximum is the first value in the vector

  • for loop which "i" will go through all the vectors

  • if "i" is greater than maximum, maximum will be the vector[[i]]

  • Then it will return maximum

#Function to find maximum
find_maximum <- function(vector){
  maximum <- vector[[1]]
  for (i in seq_along(vector)){
    if (vector[[i]] > maximum) maximum <- vector[[i]]
  }
  return(maximum)
}

CodePudding user response:

It pays dividends to insert print statements after lines you want to inspect and monitor what is happening.

find_maximum <- function(vector){
  maximum <- vector[1]
  print(sprintf("Maximum is %d", maximum))
  
  for (i in seq_along(vector)){
    print(sprintf("Investigating %d", vector[i]))
    if (vector[i] > maximum) {
      maximum <- vector[i]
      print(sprintf("Found new maximum %d", maximum))
    }
  }
  return(maximum)
}

find_maximum(vector = c(3, 5, 7, 3, 3))

[1] "Maximum is 3"
[1] "Investigating 3"
[1] "Investigating 5"
[1] "Found new maximum 5"
[1] "Investigating 7"
[1] "Found new maximum 7"
[1] "Investigating 3"
[1] "Investigating 3"
[1] 7
  • Related