I am playing with a data frame where one of the columns display the Body Mass Index (BMI) of people, and I want to create a function that takes those BMIs and returns a column with the interpretation of those BMIs (Underweight / normal / etc).
My function takes three arguments: dataframe_name, age and BMI. (The age because interpretation varies for children).
So I try to use a nested ifelse()
inside my function and the function returns a column that displays only the TRUE argument of the condition in my first ifelse()
; the others appear like NA
. But when I do the same code directly to my data frame, it works! Please help! I dont know what I am not seeing...
This is my function (imc stands for BMI in french), and its application to my table
my_function = function(tableau, age, imc){
stopifnot(age %in% colnames(tableau), imc %in% colnames(tableau))
stopifnot(is.numeric(tableau[, age]), is.numeric(tableau[, imc]))
interp = ifelse(tableau$age <= 18, "pas applicable pour enfant",
ifelse(tableau$imc < 16.5, "dénutrition",
ifelse(tableau$imc >= 16.5 & tableau$imc < 18.5, "maigreur",
ifelse(tableau$imc >= 18.5 & tableau$imc < 25, "corpulance normale",
ifelse(tableau$imc >= 25 & tableau$imc < 30, "surpoids",
ifelse(tableau$imc >= 30 & tableau$imc < 35, "obésité modérée",
ifelse(tableau$imc >= 35 & tableau$imc < 40, "obésité sévère",
ifelse(tableau$imc >= 40, "obésité morbide", "PA"))))))))
tableau = cbind(tableau, interpIMC_A = c(interp))
}
tab_preuve = my_function(tab_preuve, "age", "IMC")
This is how I did it without a function (and it work, while it didn't inside the function)
interp = ifelse(tab_preuve$age <= 18, "pas applicable pour enfant",
ifelse(tab_preuve$IMC < 16.5, "dénutrition",
ifelse(tab_preuve$IMC >= 16.5 & tab_preuve$IMC < 18.5, "maigreur",
ifelse(tab_preuve$IMC >= 18.5 & tab_preuve$IMC < 25, "corpulance normale",
ifelse(tab_preuve$IMC >= 25 & tab_preuve$IMC < 30, "surpoids",
ifelse(tab_preuve$IMC >= 30 & tab_preuve$IMC < 35, "obésité modérée",
ifelse(tab_preuve$IMC >= 35 & tab_preuve$IMC < 40, "obésité sévère",
ifelse(tab_preuve$IMC >= 40, "obésité morbide", "PA"))))))))
tab_preuve = cbind(tab_preuve, IntIMC = c(interp))
This is the table with the result without the function and with the function
Thank you to all who wants to help me (this is driving me crazy!) PS: Sorry for my english and the long post, I hope it is clear.