rvector

R - Conditionally rename vector elements


Suppose I've got a list of file names. Each file name will end in either today's date or yesterday's date. (Assume that today is 6/18/2024, so yesterday was 6/17/2024.) If I put them in a character vector, it might look like this:

    fileNames <- c("Accounts-20240617.csv", "Advisors-20240617.csv", "Customer Names-20240618.csv",
"Sales-20240617.csv", "Transactions-20240618.csv", "Users-20240617.csv")

I need to append a "t-" at the start of any file name with today's date, and a "y-" at the start of any file name with yesterday's date, so the output would look like this:

    modifiedFileNames <- c("y-Accounts-20240617.csv", "y-Advisors-20240617.csv", "t-Customer Names-20240618.csv",
"y-Sales-20240617.csv", "t-Transactions-20240618.csv", "y-Users-20240617.csv")

I can do this by writing a for loop and iterating through fileNames. Is there a way to do it purely using R's vector operations? Thanks!


Solution

  • I like lubridate::ymd for this since it will extract the date-looking data without having to remove the text on either side with some regex.

    I also like dplyr::case_when (based on SQL's CASE WHEN) as a clean way to specify multiple test conditions. e.g. you could easily add a test for "anything last week" with a single additional line.

    fileNames_dates <- lubridate::ymd(fileNames) 
    today = as.Date("2024-06-18") # or Sys.Date() but only today
    fileNames <- paste0(dplyr::case_when(
      fileNames_dates == today ~ "t-",
      fileNames_dates == today-1 ~ "y-",
      TRUE ~ ""), fileNames)
    

    Result

    [1] "y-Accounts-20240617.csv"       "y-Advisors-20240617.csv"      
    [3] "t-Customer Names-20240618.csv" "y-Sales-20240617.csv"         
    [5] "t-Transactions-20240618.csv"   "y-Users-20240617.csv" 
    

    Or a base R alternative to dplyr::case_when using nested ifelse:

    fileNames <- paste0(ifelse(fileNames_dates == today, "t-",
                               ifelse(fileNames_dates == today-1, "y-", "")), 
                        fileNames)