Reputation: 43
So I have been doing some project in which I am using multiple if-else-if conditions, the issue that I am facing is, whenever the first condition is met, the entire column is filled with that value itself, and it doesn't check further conditions.
This the code snippet that I am using :
rdw_acct_dedup$PROCESS <- if (substr(rdw_acct_dedup$STATUS_CD,1,1) == 'S')
{
rdw_acct_dedup$PROCESS <- '01)SOLD'
}else if(substr(rdw_acct_dedup$STATUS_CD,1,3) %in% c('894','895','910','994','D96','I25','I26','I27','Q34','V90','919','99F','99Q','D97','931','V22'))
{
rdw_acct_dedup$PROCESS <- '02)SIF-SETTLED'
}else if(substr(rdw_acct_dedup$STATUS_CD,1,3) %in% c('899','I45','PDV','U10','U39','V63'))
{
rdw_acct_dedup$PROCESS <-'03)SIF-PENDING'
}else if(substr(rdw_acct_dedup$STATUS_CD,1,1) == 'B')
{
rdw_acct_dedup$PROCESS <- '04)BANKRUPTCY'
}else if(substr(rdw_acct_dedup$STATUS_CD,1,1) == 'V')
{
rdw_acct_dedup$PROCESS <- '05)PRE-BANKRUPTCY'
}else
{
rdw_acct_dedup$PROCESS <-'18)OTHER'
}
So even if the first condition is met entire process columns gets filled with '01)SOLD'
Upvotes: 0
Views: 72
Reputation: 6685
Just a quick glance at how you could do it with nested ifelse()
:
df <- data.frame(status = c("S104", "894T", "899X", "B67", "VXT", "ABC"))
status
1 S104
2 894T
3 899X
4 B67
5 VXT
6 ABC
df$process <- with(df, ifelse(substr(status, 1, 1) == "S", "SOLD",
ifelse(substr(status, 1, 3) %in% c("894"), "SIF-SETTLED",
ifelse(substr(status, 1, 3) %in% c("899"), "SIF-PENDING",
ifelse(substr(status, 1, 1) == "B", "BANKRUPTCY",
ifelse(substr(status, 1, 1) == "V", "PRE-BANKRUPTCY", "OTHER"))))))
status process
1 S104 Sold
2 894T SIF-SETTLED
3 899X SIF-PENDING
4 B67 BANKRUPTCY
5 VXT PRE-BANKRUPTCY
6 ABC OTHER
You'd need to include all the relevant numbers into the vectors for the %in%
conditions, I was too lazy :)
Upvotes: 1