If the following data table is given, and we would like to compare x1 consequently with x2 to x5, the following can be used:
TDT <- data.table(x1 = sample(100,100),
x2 = round(rnorm(100,0.75,0.3),2),
x3 = round(rnorm(100,0.75,0.3),2),
x4 = round(rnorm(100,0.75,0.3),2),
x5 = round(rnorm(100,0.75,0.3),2))
TDT[,compare := ifelse(x1 < x2,1,ifelse(x1 < x3,2,ifelse(x1 < x4,3,ifelse(x1 < x5,4,5))))]
So if x1 < x2, then compare == 1, etc.
Now in my example, I have a lot more columns to compare x1 with. Is there any way to write this more concisely, i.e. without nested ifelse?
Aucun commentaire:
Enregistrer un commentaire