I came across an issue while converting one of if.. else condition to ifelse () in R to make the process faster. In this question, I have to use the value from the previous row if the condition is met. I was not able to replicate the same results from my code Below is the if.. else statement and its converted code.
for (i in 1:nrow(newdata)){
if ((newdata$first == 1)){
newdata[, decvar][i] = groups + 1 - ceiling(round((newdata$cum/total) * groups, 4))
} #calculate decile; if var = 0, decile = 0
else if (newdata$first == 0){
newdata[, decvar][i] = newdata[, decvar][i-1]
}
}
Using ifelse():
brv_trx1$decvar <- ifelse(((brv_trx1$first == 1)),(11 - ceiling(round((brv_trx1$cum/total) * 10, 4))), ifelse(((brv_trx1$first == 0)), lag(brv_trx1$decvar) ,NA))
The sample output will look something like this :
variable First Decvar
45 1 10
42 1 10
31 1 9
30 0 9
30 0 9
29 0 8
29 0 8
28 0 8
21 1 7
I was getting some output as 0, which I have no clue where it came from
Aucun commentaire:
Enregistrer un commentaire