Insertion of intervals with the if Else condition structure

Asked

Viewed 216 times

2

Consider the vector and function:

j <- 1:10

my_fun <- function(x) {
  sapply(x, function(x) {
    if (x == 5) {
      ('EM ANALISE')
    } else if (x < 5) {
      ('REPROVADO')
    } else if (x > 5) {
      ('APROVADO')
    }
  })
}

my_fun(j)

 [1] "REPROVADO"  "REPROVADO"  "REPROVADO"  "REPROVADO"  "EM ANALISE" "APROVADO"  
 [7] "APROVADO"   "APROVADO"   "APROVADO"   "APROVADO" 

How to select the interval between 3 and 4.9 and insert the category RECUPERAÇÃO, so that the result:

[1] "REPROVADO"  "REPROVADO" "RECUPERAÇÃO" "RECUPERAÇÃO" "EM ANALISE" "APROVADO"  
[7] "APROVADO"   "APROVADO"   "APROVADO"   "APROVADO" 

Also, how to use a for instead of sapply and get the same result?

1 answer

2


Are not necessary if nor cycles for or *apply.
Here are two ways to do what you want.

1. One can use the cut.

my_fun2 <- function(x){
  menor_que_5 <- 5 - .Machine$double.eps^0.5
  brks <- c(-Inf, 3, menor_que_5, 5, Inf)
  labs <- c('REPROVADO', 'RECUPERAÇÃO', 'EM ANALISE', 'APROVADO')
  res <- cut(x, breaks = brks, labels = labs, 
             include.lowest = TRUE, right = FALSE)
  as.character(res)
}

my_fun2(1:10)

2. Another way is to use the findInterval.

my_fun3 <- function(x){
  menor_que_5 <- 5 - .Machine$double.eps^0.5
  brks <- c(-Inf, 3, menor_que_5, 5, Inf)
  labs <- c('REPROVADO', 'RECUPERAÇÃO', 'EM ANALISE', 'APROVADO')
  i <- findInterval(x, brks)
  labs[i]
}

my_fun3(1:10)

3. Now with ifelse.

my_fun4 <- function(x) {
  menor_que_5 <- 5 - .Machine$double.eps^0.5
  ifelse (x == 5, 'EM ANALISE',
          ifelse(x < 3, 'REPROVADO',
                 ifelse(x < menor_que_5, 'RECUPERAÇÃO', 'APROVADO')))
}

my_fun4(1:10)

4. And finally with a cycle for.

my_fun5 <- function(x) {
  n <- length(x)
  y <- character(n)
  for(i in seq_len(n)){
    y[i] <- if (x[i] < 3) {
      'REPROVADO'
    } else if (x[i] < 5) {
      'RECUPERAÇÃO'
    } else if (x[i] == 5) {
      'EM ANALISE'
    } else if (x[i] > 5) {
      'APROVADO'
    }
  }
  y
}

my_fun5(1:10)
  • I appreciate the answer, Rui. But, by necessity, I need to solve this problem under these conditions.

  • 1

    @user108927 Made with ifelse and with for.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.