user35131
user35131

Reputation: 1134

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

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"

Upvotes: 0

Views: 23

Answers (2)

Robert Hacken
Robert Hacken

Reputation: 4725

You can use sub:

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

Upvotes: 2

Mike
Mike

Reputation: 4370

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("%02d",seq_along(x)), sep = "_")

Upvotes: 1

Related Questions