Created
November 20, 2023 15:05
-
-
Save jmcastagnetto/68a81995db2fdb602adc5080d5f4c347 to your computer and use it in GitHub Desktop.
Ejemplo de uso de "if ... else ..." en R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
v1 <- LETTERS[1:20] | |
v1 | |
for (i in 1:length(v1)) { | |
if (i %% 2 == 0) { | |
v1[i] <- tolower(v1[i]) | |
} else { | |
v1[i] <- "-" | |
} | |
} | |
v1 | |
# dataframe original | |
hemoglobina <- data.frame( | |
sexo= c(rep("M", 5), rep("F", 5)), | |
hb = c(14.1, 14.8, 12.5, 11.0, 13.9, | |
10.1, 11.2, 12.1, 13.0, 14.6) | |
) | |
# código estilo base R | |
hemoglobina2 <- hemoglobina | |
hemoglobina2$anemia <- ifelse( | |
hemoglobina$sexo=="M", | |
ifelse( | |
hemoglobina$hb < 13, | |
"Sí", | |
"No" | |
), | |
ifelse( | |
hemoglobina$hb < 12, | |
"Sí", | |
"No" | |
) | |
) | |
# código estilo tidyverse | |
hemoglobina3 <- hemoglobina %>% | |
mutate( | |
anemia = if_else( | |
(sexo == "M" & hb < 13) | | |
(sexo == "F" & hb < 12), | |
"Sí", | |
"No" | |
) | |
) | |
all.equal(hemoglobina2, hemoglobina3) | |
# código con for, if...else | |
hemoglobina4 <- hemoglobina | |
hemoglobina4$anemia <- NA # inicializar la nueva var | |
for (i in 1:nrow(hemoglobina)) { | |
s <- hemoglobina4[i, ]$sexo | |
h <- hemoglobina4[i, ]$hb | |
if ((s == "M" & h < 13) | (s == "F" & h < 12)) { | |
hemoglobina4[i, ]$anemia <- "Sí" | |
} else { | |
hemoglobina4[i, ]$anemia <- "No" | |
} | |
} | |
all.equal(hemoglobina2, hemoglobina4) | |
if (all.equal(hemoglobina2, hemoglobina3) == TRUE) { | |
print("Happy!") | |
} else { | |
print("Sad...") | |
} | |
if (sum(letters[1:2] == c("a", "b")) == 2) { | |
print("😊") | |
} else { | |
print("😞") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment