Calculating columns with conditional in R

Asked

Viewed 186 times

2

I have the following table df

Valor DebCred
100     C
200     D
300     C

I have to create a logic that is the following if Table DebCred for C I have to multiply Valor * -1,00 and if it equals D multiply Valor*0.

I made a code that would be the following

IF (df$DebCred == C){
    df$Cred <- df$Valor * -1
}else{
    df$Cred <- df$Valor * 0 
}
IF (df$DebCred == D){
    df$Deb <- df$Valor * 1
}else{
    df$Deb <- df$Valor * 0 
}

2 answers

3


A vector way is the following. It uses logical indexes to modify the column Valor.

df$Valor[df$DebCred == 'C'] <- -1*df$Valor[df$DebCred == 'C']
df$Valor[df$DebCred == 'D'] <- 1*df$Valor[df$DebCred == 'D']
df$Valor[!df$DebCred %in% c('C', 'D')] <- 0

df
#  Valor DebCred
#1  -100       C
#2   200       D
#3  -300       C

0

One efficient way to handle these cases is with the function mutate(), of tydiverse.

Follows the code:

library(tidyverse)

df = data.frame(Valor = c(100, 200, 300),
                DebCred = c("C", "D", "C"))

df %>% mutate(result = case_when(DebCred == "C" ~ Valor*-1,
                                 DebCred == "D" ~ Valor*0))

  Valor DebCred result
1   100       C   -100
2   200       D      0
3   300       C   -300

If your intention was to store the results in the column Valor instead of creating a new column, just inside the mutate do the following:

df %>% mutate(Valor = case_when(DebCred == "C" ~ Valor*-1,
                                DebCred == "D" ~ Valor*0))
 Valor DebCred
  -100       C
     0       D
  -300       C

Browser other questions tagged

You are not signed in. Login or sign up in order to post.