0

I am trying to name a column based on info from the filename of the imported data. My data looks like this

Sample Data
Folder1/Folder2/FileName_1.txt 124321
Folder1/Folder2/FileName_2.txt 5436

etc.

I am looking to change this to

Sample Data
FileName 124321
FileName 5436

My code currently uses this

testfiles2 <- testfiles %>%
mutate(Sample = sub(pattern = ".*[0-9]", replacement = "", Sample))

but I am unable to find the syntax for the pattern arguement to remove the filepath except for the filename from the sample value. Does this make sense?

Edit: This was marked resolved and is not. The solution in that page does not address this:

However, sometimes I have multiple reps of a Sample and each file name looks something like this: Sample_1 and Sample_2. How can I make it so both of these are left as only reading Sample ?

Thank you.

oguz ismail
  • 1
  • 16
  • 47
  • 69
user7264
  • 123
  • 8
  • `Sample = sub('[.].*', '', basename(Sample))` – Onyambu Jul 14 '22 at 20:08
  • `Sample = tools::file_path_sans_ext(basename(Sample))` – Onyambu Jul 14 '22 at 20:10
  • @onyambu Thank you, that leaves me with just the filename as what is left. However, sometimes I have multipel reps of a Sample and each file name looks something like this: `Sample_1` and `Sample_2`. How can I make it so both of these are left as only reading `Sample` ? – user7264 Jul 14 '22 at 21:48
  • Figured it out. mutate(Sample = sub("[.].*", '', basename(Sample))) %>% mutate(Sample = sub("_.*[0-9]", '', basename(Sample))) %>% – user7264 Jul 15 '22 at 18:31

0 Answers0