mercredi 3 juillet 2019

Conditional assignment of values in R: Comparison of methods and best practice

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 <- 1 if y > 10 & y <= 20
  • x <- 2 if y > 20 & y <= 30
  • x <- 3 if y > 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