use str_detect for month names in list and replace them with numeric values in r

59 views Asked by At

I want to create a function for detecting the month names from list of filenames and replace the month names with a numeric value. Can we use a dictionary for creating such function and apply to the list.

f <- c("cm18OCT2023.csv", "cm22NOV2023.csv")

month_text <- c("JAN" = "01",
                "FEB" = "02",
                "MAR" = "03",
                "APR" = "04",
                "MAY" = "05",
                "JUN" = "06",
                "JUL" = "07",
                "AUG" = "08",
                "SEP" = "09",
                "OCT" = "10",
                "NOV" = "11",
                "DEC" = "12")



newnames <- ifelse(str_detect(f, names(month_text)), new_names, f)

The final output can be of new names such as paste0("23", value(month_text), str_sub(3,4),".csv") for a new list.

2

There are 2 answers

0
jay.sf On

You could have this cheaper using the built-in month.abb.

> sprintf('%02d', match(f, toupper(month.abb)))
 [1] "08" "12" "06" "10" "09" "01" "02" "04" "03" "11" "07" "05"

Data:

> dput(f)
c("AUG", "DEC", "JUN", "OCT", "SEP", "JAN", "FEB", "APR", "MAR", 
"NOV", "JUL", "MAY")
0
Onyambu On

use strptime + format:

format(strptime(f, "cm%d%b%Y"), "%d_%m_%Y.csv") # added _ to the text
[1] "18_10_2023.csv" "22_11_2023.csv"

type ?strptime on your console to see all the formats. Note that we have %b for month abbreviations and %m for month numeric