Reputation: 448
Using only the pattern
argument from the list.files()
function how could I get a file list excluding some files with similar pattern?
Let's say I have this files in my working directory:
med_t_1_1.csv, 01_t_1_1.csv, 02_t_1_1.csv, 03_t_1_1.csv,
med_t_2_1.csv, 01_t_2_1.csv, 02_t_2_1.csv, 03_t_2_1.csv
I want to get the files with the pattern t_1_1 but the one that starts with med:
01_t_1_1.csv, 02_t_1_1.csv, 03_t_1_1.csv
Upvotes: 1
Views: 281
Reputation: 13591
You can use regular expression
S[grepl("(?<!med_)t_1_1", S, perl=TRUE)]
# "01_t_1_1.csv" "02_t_1_1.csv" "03_t_1_1.csv"
Explanation of regex
(?<!med_)
= (?<
looks behind, !
does not match, med_
is the string
Look behind for string that does not match the string med_
t_1_1
= t_1_1
is string
Look for any string that matches t_1_1
**Other example
S1 <- c("med_t_1_1.csv", "S_t_1_1.csv", "04_t_1_1.csv")
S1[grepl("(?<!med_)t_1_1", S1, perl=TRUE)]
# "S_t_1_1.csv" "04_t_1_1.csv"
Upvotes: 2
Reputation: 10671
file_chrs <- c("med_t_1_1.csv", "01_t_1_1.csv", "02_t_1_1.csv", "03_t_1_1.csv",
"med_t_2_1.csv", "01_t_2_1.csv", "02_t_2_1.csv", "03_t_2_1.csv")
file_chrs[grepl("\\d_t_1_1", file_chrs)] # \\d matches and digit [0-9]
# console
[1] "01_t_1_1.csv" "02_t_1_1.csv" "03_t_1_1.csv"
# so in your working directory
list.files( pattern = "\\d_t_1_1" )
Upvotes: 2