Strings and Dates
Pattern Matching
Finding File Names
grepl returns a logical vector showing which strings match a pattern.
Program
Play the script to keep only names ending in .csv.
grepl_patterns.R
Replay: real traced execution (multi-file project)
files <- c("report.csv", "notes.txt", "sales.csv")
csv_files <- files[grepl("\\.csv$", files)]
count <- length(csv_files)
cat(count, "\n", sep = "")
files ← report.csv, notes.txt, sales.csv
1files <- c("report.csv", "notes.txt", "sales.csv")2csv_files <- files[grepl("\\.csv$", files)]values this stepreport.csv, notes.txt, sales.csvfilescsv_files ← report.csv, sales.csv
1files <- c("report.csv", "notes.txt", "sales.csv")2csv_files <- files[grepl("\\.csv$", files)]3count <- length(csv_files)values this stepreport.csv, sales.csvcsv_filesreport.csv, notes.txt, sales.csvfilescount ← 2
2csv_files <- files[grepl("\\.csv$", files)]3count <- length(csv_files)4cat(count, "\n", sep = "")values this step2countreport.csv, sales.csvcsv_filescat(count, " ", sep = "")
3count <- length(csv_files)4cat(count, "\n", sep = "")output2values this step2count
Follow the Filter
filesstarts asreport.csv,notes.txt, andsales.csv.grepl("\\.csv$", files)checks whether each name ends with.csv.report.csvmatches and stays selected.notes.txtdoes not match, whilesales.csvdoes.countbecomes2, so the script prints2. | file | matches.csvat end? | selected | | --- | --- | --- | | report.csv | TRUE | yes | | notes.txt | FALSE | no | | sales.csv | TRUE | yes |
grepl
`grepl(pattern, files)` returns `TRUE` or `FALSE` for each file name.
regular expression
`\\.csv$` means a literal `.csv` at the end of the string.
length
`length(csv_files)` counts selected vector elements.
Exercise: grepl_patterns.R
Reproduce the printed count 2, then trace which two file names are selected.