Slangers
Slangers

Reputation: 117

Filter list of files according vector (import specificied png)

So I have a list of characters which contains names of png's I want to import. It is on the form:

names =  c("791365", "731823CK", "791652", "74164", "194817MKZ", "EK791073")

The names differ in both size and setup. These are the names of the png's I want to load. In the folder I'm loading from there are 1000's of png's but I only want to load the ones that have the names in my vector of names. I have loaded the paths for all the PNG's but strugge to filter so that only the names in my vector are loaded.

imgs <- list.files(path =".../Desktop/PNGs", pattern = ".png", all.files = TRUE, full.names = TRUE)

I think a way of doing this could be lapply, but I am not sure. Is there a smart way of doing this?

Upvotes: 1

Views: 62

Answers (2)

pogibas
pogibas

Reputation: 28369

This command extracts files from imgs that contain string from names in their file name.

First we use basename to remove path to file (we don't want to grep that). Next we get rid off .png extension. Then we search for names in our modified file names and extract original imgs string.

imgs[grep(paste0("^", names, ".png$", collapse="|"), basename(imgs))]

Upvotes: 1

tbradley
tbradley

Reputation: 2290

You can use the Filter() function.

Filter(function(x) grepl(x, imgs), names)

Upvotes: 1

Related Questions