Suppose I want to assign different values to x conditional on some other variables. If there are only two conditions, I could use ifelse. For more than two conditions, I would use if-else-statements. For example, suppose I wanted to make the following assignments:
x <- 1ify > 10 & y <= 20x <- 2ify > 20 & y <= 30x <- 3ify > 30 & y <= 50
Normally, I would implement this in the following way (method 1):
if (y > 10 & y <= 20) {
x <- 1
} else if (y > 20 & y <= 30) {
x <- 2
} else if (y > 30 & y <= 50) {
x <- 3
}
But I recently saw another way (method 2):
x <- if (y > 10 & y <= 20) {
1
} else if (y > 20 & y <= 30) {
2
} else if (y > 30 & y <= 50) {
3
}
Questions:
- Are there any differences between method 1 and method 2 except personal preferences that I should be aware of (e.g. performance)?
- What are the advantages and disadvantages of both methods, if any?
- Are there other methods you would recommend?
Aucun commentaire:
Enregistrer un commentaire