From a filelist how do i read the csv that begin with numbers and add before blank to the back of the string seperated by a underscore using r?

Viewed 21

For example I begin by pulling the dataset like this

#set the directory
setwd("C//Users//Project")


filestoread <- list.files(pattern = "^.*\\.csv$")


#list them in the Data
filelist=lapply(filestoread, read.csv)

Everything works fine. One thing to note is the files are named

"40 Jersey Number", "66 Jersey Number", "879 Jersey Number", "565 Jersey Number"

Normally Jersey Number contain two digits and i would request a script that would rename the files in the list to pull the first two digits and shift them to the back. However I want a script that would create

"Jersey Number_40","Jersey Number_66", "Jersey_Number_879", and "Jersey_Number_565"

Basically something that would take the number in front by recognizing it up until the first blank where it then takes that chunk and shifts it to the back but not including the white space after the number preceded by a underscore.

I believe it would start like this

names(filelist) <- ..........
1 Answers

We can use sub to capture one or more digits (\\d+) at the beginning of the string (^) followed by a space, then capture the second word (\\w+) and the third word, in the replacement, rearrange the backreference (\\1, \\2,\\3) of the captured group

names(filelist) <-  sub("^(\\d+) (\\w+) (\\w+)", "\\2 \\3_\\1", v1)
names(filelist)
#[1] "Jersey Number_40"  "Jersey Number_66"  "Jersey Number_879" "Jersey Number_565"

data

v1 <- c("40 Jersey Number", "66 Jersey Number", "879 Jersey Number", "565 Jersey Number")
Related