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.
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