ShanZhengYang ShanZhengYang - 1 year ago 104
R Question

How to create a new R vector by filtering with grepl()?

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
object for each "type" of file, e.g.
, 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(".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

Answer Source

You can use the logical vector produced by grepl() to index vec.

txt_paths <- vec[grepl(".txt$", vec)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download