Home > Net >  How to rename values from list based on information provided in the list name
How to rename values from list based on information provided in the list name

Time:09-29

I have 4 values in the list

c("JSMITH_WWWFRecvd2001_asof_20220901.xlsx", "WSMITH_AMEXRecvd2002_asof_20220901.xlsx",
"PSMITH_WWWFRecvd2003_asof_20220901.xlsx", "QSMITH_AMEXRecvd2004_asof_20220901.xlsx")

I would like my outcome to be

"wwwf_01","amex_02","wwwf_03","amex_04"

CodePudding user response:

You can use sub:

tolower(sub('. _(. )Recvd[0-9][0-9](..). ', '\\1_\\2', x))

CodePudding user response:

Something like this would work. You can extract the string you want with str_extract() make it lower case with tolower() and paste the formatted counter to the end of the string with a "_" separator =.

paste(tolower(stringr::str_extract(x,"WWWF|AMEX" )), sprintf("d",seq_along(x)), sep = "_")
  • Related