Search code examples
rtidyverse

Add suffix to variable value conditional on another variable


Given the data below, what is the easiest way to add a suffix to the variable 'var' depending on the value of 'type'? So for example, if type = "white", add "_t" to the end of each value of var, and add "_b" if type = "black".

structure(list(var = c("test", "test", "score", "score", "base", 
"base"), type = c("white", "black", "white", "black", "white", 
"black")), row.names = c(NA, -6L), spec = structure(list(cols = list(
    var = structure(list(), class = c("collector_character", 
    "collector")), type = structure(list(), class = c("collector_character", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0000024d0c9a2b10>, class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"))

Solution

  • We can use dplyr::case_when():

    library(tidyverse)
    
    dat %>% 
      mutate(var = case_when(type == "white" ~ paste0(var, "_t"),
                             type == "black" ~ paste0(var, "_b"))
             )
    #> # A tibble: 6 × 2
    #>   var     type 
    #>   <chr>   <chr>
    #> 1 test_t  white
    #> 2 test_b  black
    #> 3 score_t white
    #> 4 score_b black
    #> 5 base_t  white
    #> 6 base_b  black
    

    data from OP

    dat <- structure(list(var = c("test", "test", "score", "score", "base", 
                           "base"),
                   type = c("white", "black", "white", "black", "white", 
                                             "black")),
              row.names = c(NA, -6L),
              class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"))
    

    Created on 2023-02-20 with reprex v2.0.2