mardi 31 août 2021

"Argument is of length zero" error in if argument - comparing two values in a vector

My code looks like this:

min_max <- function(n) {
  # n is the length of the given vector
  vecc <- rep(0, length = n)
  for (i in 1:n) {
    v <- as.integer(readline(prompt = "Insert number: "))
    vecc[i] <- v
    print(typeof(v[i]))
  }
  vecc <- as.integer(vecc)
  for (i in 1:n - 1) {
    print(vecc[i])
    if (vecc[i] > vecc[i + 1]) {
      aux <- vecc[i]
      vecc[i] <- vecc[i + 1]
      vecc[i + 1] <- aux
    }
  }

  print(vecc[1])
  print(vecc[n])
}
min_max(4)

And the result is an error

"argument is of length zero"

I am new to the R language and I really don't know how to solve this. I tried giving the vector using c() and then using the min, max functions and this is a way to solve the problem itself, but what should I do when I have to compare/ sort values of a given vector?

Aucun commentaire:

Enregistrer un commentaire