0

Context: I'm trying to create a vector with IMC values and then pass the values from this vector to perform an if statement (adding a new column called Gr_IMC with specific values). I've tried searching in SO and doing these ideas from this topic (Append value to empty vector in R?), but I keep getting all the rows from the Gr_IMC column as "Peso Normal".

Code:

for (j in 1:100) {
  IMC_values = c(((dados$Peso[j])/(dados$Altura[j]^2) * 10000))

  for (i in IMC_values) {
    if (i < 18.5) {
    dados$Gr_IMC = "Abaixo do peso ideal"
  } else if (i >= 18.5 && i < 25) {
    dados$Gr_IMC = "Peso normal"
  } else if (i >= 25 & i < 30) {
    dados$Gr_IMC = "Acima do peso ideal"
  } else {
    dados$Gr_IMC = "Obesidade"
  }
  }
}

How could I make this so that the vector IMC_values does the calculation of the IMC from my date and appends the previous elements?

Thank you in advance

1 Answers1

0

You can try a vectorised pattern using cut() instead of for loop. The output is a factor which can be converted to character as necessary. You can specify the vector for breaks as you want. Here is an example using a dummy data frame.

Using within(), we can avoid repeating the name of data frame.

dados <- data.frame(
  peso = 1:5,
  altura = ((1:5)/10000)^(-0.5)
)

dados

# peso    altura
#    1 100.00000
#    2  70.71068
#    3  57.73503
#    4  50.00000
#    5  44.72136

dados <- within(dados, {
  IMC_values <- peso/(altura^2) * 10000
  Gr_IMC <- cut(IMC_values, breaks = c(0, 5, 15, 25),
                labels = c("Albaixo do peso ideal", "Peso normal", "Obesidade"))
  Gr_IMC <- as.character(Gr_IMC)
})

dados

# peso    altura                Gr_IMC IMC_values
#    1 100.00000 Albaixo do peso ideal          1
#    2  70.71068 Albaixo do peso ideal          4
#    3  57.73503           Peso normal          9
#    4  50.00000             Obesidade         16
#    5  44.72136             Obesidade         25
Zaw
  • 1,434
  • 7
  • 15