CcS
CcS

Reputation: 143

How to vectorize this ifelse statement?

I have the following ifelse statement where $TotalReplacementRatio is a column with numbers from 0-1.5. It's dragging my for loop, so I want to vectorize it.

 ModelOutputTRA$RetirementReady <- ifelse(ModelOutputTRA$TotalReplacementRatio > RetReadiness,"Yes","Not")

I tried the following alternative to make it run faster in a loop, but I get an error:

rrv1 <- ModelOutputTRA$TotalReplacementRatio >= RetReadiness 
rrv2 <- ModelOutputTRA$TotalReplacementRatio < 0 
  
ModelOutputTRA$RetirementReady[rrv1] <- "Yes"
ModelOutputTRA$RetirementReady[rrv2] <- "Not"

The rrv1 obviously creates a logical vector, which I want to use to filter the column and insert the factor levels shown. Is that possible?

I will end up repeating this process for another ifelse inside my for loop:

ModelOutputTRA$SSLevel <- ifelse(ModelOutputTRA$FinalSalary >= ModelOutputTRA$FinalSSHigh,"High",ifelse(ModelOutputTRA$FinalSalary >= ModelOutputTRA$FinalSSLow,"Mid","Low"))

Upvotes: 1

Views: 65

Answers (1)

akrun
akrun

Reputation: 886948

If we need to vectorize, convert the logical vector to numeric index (in R, indexing starts from 1, so TRUE/FALSE -> 1/0, added 1 -> 2/1) and this can be used to replace a vector based on the position

c("Not", "Yes")[1 + (ModelOutputTRA$TotalReplacementRatio > RetReadiness)]

For multiple comparisons, use case_when

library(dplyr)
with(ModelOutputTRA, case_when(SSLevel >= FinalSSHigh ~ "High",
   FinalSalary >= FinalSSLow ~ "Mid",
   TRUE ~ "Low"))

Upvotes: 1

Related Questions