'How to prevent ifelse statement from clearing out previous data?

I'm trying to import some accounting data to a new software and need to add a debit column journalItemLine_debitAmount and a credit column journalItemLine_creditAmount that are filled if there is a debit or credit in the source data. When I run my script, I end with only the data marked Credit when positive and none of the Debit when positive data.

data = within(data, {
journalItemLine_debitAmount = ifelse(If.Positive. == "Debit" & Amount>=0, Amount, "")
journalItemLine_creditAmount = ifelse(If.Positive. == "Debit" & Amount<0, -Amount, "")
journalItemLine_debitAmount = ifelse(If.Positive. == "Credit" & Amount<0, -Amount, "")
journalItemLine_creditAmount = ifelse(If.Positive. == "Credit" & Amount>=0, Amount, "")
 })

Here's the source data:

Amount  If.Positive.
0.00    Debit
-546    Debit
789     Credit
45789   Debit
-34657  Credit

Here's what I would like:

Amount     If.Positive.     journalItemLine_debitAmount     journalItemLine_creditAmount
0.00       Debit            0
-546       Debit            546
789        Credit                                           789
45789      Debit            45789
-34657     Credit                                           34657

I also tried this if statement but nothing seemed to happen.

journalItemLine_debitAmount = if((If.Positive. == "Debit") && (Amount>=0)){Amount}
journalItemLine_creditAmount = if((If.Positive. == "Debit") && (Amount<0)){-Amount}
journalItemLine_debitAmount = if((If.Positive. == "Credit") && (Amount<0)){-Amount}
journalItemLine_creditAmount = if((If.Positive. == "Credit") && (Amount>=0)){Amount}
})


Solution 1:[1]

you could also try as:

data$journalItemLine_debitAmount[If.Positive. == "Debit" & Amount>=0]<- Amount
data$journalItemLine_debitAmount[If.Positive. == "Debit" & Amount<0] <- -Amount
data$journalItemLine_creditAmount[If.Positive. == "Credit" & Amount<0] <- -Amount
data$journalItemLine_creditAmount[If.Positive. == "Credit" & Amount>=0] <- Amount

or simpler:

data$journalItemLine_debitAmount[If.Positive. == "Debit"]<- abs(Amount)
data$journalItemLine_creditAmount[If.Positive. == "Credit"] <- abs(Amount)

Hope it helps!

Solution 2:[2]

I think you just want

data = within(data, {
  journalItemLine_debitAmount = ifelse(
    (If.Positive. == "Debit" & Amount>=0) | (If.Positive. == "Credit" & Amount<0),
     abs(Amount), NA)
  journalItemLine_creditAmount = ifelse(
     (If.Positive. == "Credit" & Amount>=0) | (If.Positive. == "Debit" & Amount<0),
     abs(Amount), NA)
})

This avoids reassigning to the same value twice and just uses the absolute value to keep the number positive.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Constanza Garcia
Solution 2