Home > Net >  Replace existing df values not adding a new column
Replace existing df values not adding a new column

Time:03-15

df %>%
  mutate(NewQty = case_when(
                           Week == "202001" && 
                              Category == "Category1" ~ (Qty*0.05),
                           Week == "202001" && 
                              Category == "Category2" ~ (Qty*0.25),
                           TRUE ~ NA_real_))

I would like to execute this without it creating a new column titled "NewQty" because I am using this df later in my code. Additionally would it be possible instead of when Week equals "202001" to just do this when the week begins with 2020?

Here is my dataframe before execution

Week    Category    Qty
202001  Category1   100
202001  Category2   115
202002  Category1   95
202002  Category2   105

CodePudding user response:

You may use grepl():

df %>%
    mutate(NewQty = case_when(
        grepl("^2020", Week) & Category == "Category1" ~ (Qty*0.05),
        grepl("^2020", Week) & Category == "Category2" ~ (Qty*0.25),
        TRUE ~ NA_real_)
    )

Note that you want to use &, not &&, for logical and here between vectors.

CodePudding user response:

Posting as a new answer for clarity, also including the approach from the accepted answer.

This should work to replace the Qty column with the calculated values where the conditions are met. Where the conditions are not met, it will use the original value from Qty.

df %>%
  mutate(Qty = case_when(
                           grepl("^2020", Week) & Category == "Category1" ~ (Qty*0.05),
                           grepl("^2020", Week) & Category == "Category2" ~ (Qty*0.25),
                           TRUE ~ Qty))
  •  Tags:  
  • r
  • Related