Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to map a column of sample ID's to their respective filename

I have a dataframe which contains a column called sample_id amongst other metadata.

df <- data.frame(sample_id = c('x1', 'x2', 'x3', 'x4'))

I also have a list of files that contain their respective filenames which might not always have the same suffix.

files <- list('x1_001.txt', 'x2_003.txt', 'x4_abc.txt', 'x3_bg.txt')

I’d like to create a column in the data frame that greps the filename from the list of files and maps it to the respective sample_id.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However when I try to do that with df <- df %>% mutate(filename = grep(sample_id, files, value = TRUE) it doesn’t work.

Is there a function that has this capability or would I need to create something custom?

Thank you for any help.

df <- df %>% mutate(filename = grep(sample_id, files, value = TRUE)

>Solution :

It may be easier to extract the substring from the file names with sub and do a match with the ‘sample_id’ column and then reorder the files based on the numeric index

v1 <- unlist(files)
df$filename <- v1[match(df$sample_id, sub( "_.*", "", v1))]

-output

> df
  sample_id   filename
1        x1 x1_001.txt
2        x2 x2_003.txt
3        x3  x3_bg.txt
4        x4 x4_abc.txt
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading