This is a straightforward problem, but I'm missing something below.
I have a very large vector of filepaths (i.e. strings) in R
vec = c("\dir\subdir\pathname1\file.txt", "\dir\subdir\pathname1\file.pdf",
..., "\dir\subdir\pathname9\file.jpg")
My idea is to create a data.table
object for each "type" of file, e.g. .txt
, .pdf
, etc. Therefore, I need an R vector for each file extension by filtering the above.
The way I would search for strings with certain extensions is grepl()
:
grepl(".txt$", vec)
Now, how do I create a new vector using grepl()? The end point should be
txt_paths <- # single vector only with txt files
pdf_paths <- # single vector only with pdf files
jpg_paths <- # single vector only with jpg files
etc.
You can use the logical vector produced by grepl() to index vec.
txt_paths <- vec[grepl(".txt$", vec)]