Search code examples
rif-statementdataframein-operator

Replace value of an existing column based on whether it's present in a list


I have a sample data frame as such:

dat <- data.frame(V1 = c("Non Debt Balance","Non Debt Income","Non Debt Cost"), 
              V2 = c("Average Balance","Income","Cost"), 
              V3 = c("Trade","Sales Finance","Trade"))

I would like to create a new column based on the value of column V2. If column V2 is %in% ("Income","Cost") then I would like the new column to pick column V3, if not in the list then V2.

I was thinking about using the %in% function but not sure how I would go about doing an if in this list then get this column else get this column logic.

Help is most appreciated. Regards,


Solution

  • Is this what you're looking for?

    library(dplyr)
    
    dat %>% 
      mutate(V4 = case_when(V2 == "Income" | V2 == "Cost" ~ V3,
                            TRUE ~ V2))
    
                    V1              V2            V3              V4
    1 Non Debt Balance Average Balance         Trade Average Balance
    2  Non Debt Income          Income Sales Finance   Sales Finance
    3    Non Debt Cost            Cost         Trade           Trade
    

    Alternatively, using %in% as you mentioned:

    dat %>% 
      mutate(V4 = case_when(V2 %in% c("Cost", "Income") ~ V3,
                            TRUE ~ V2))
    

    Data:

    dat <- data.frame(V1 = c("Non Debt Balance","Non Debt Income","Non Debt Cost"), 
                      V2 = c("Average Balance","Income","Cost"), 
                      V3 = c("Trade","Sales Finance","Trade"),
                      stringsAsFactors = FALSE)