I’m looking for a way to filter the contents of each data frame in a list df_list by the contents of some single data frame containing my criteria.
In this case, I have a ton of sample data from an image, where each object in the image was identified by coordinates. I only want a specific subset of the objects, but the coordinate range of those objects changes from image to image.
Here are some example data:
image_a <- data.frame(
X = c(1, 10),
Y = c(5, 12),
CritA = c("aln", "cbra"),
CritB = c(21, 117)
)
image_b <- data.frame(
X = c(12, 25),
Y = c(50, 35),
CritA = c("asdf", "bzt"),
CritB = c(90, 105)
)
df_list <- list(ImageA = image_a, ImageB = image_b)
$ImageA
X Y CritA CritB
1 1 5 aln 21
2 10 12 cbra 117
$ImageB
X Y CritA CritB
1 12 96 asdf 90
2 35 99 bzt 105
filter_coords <- data.frame(
image = c(ImageA, ImageB),
Xmin = c(2, 32),
Ymin = c(3, 95),
Xmax = c(12, 48),
Ymax = c(30, 102)
)
filter_coords
image Xmin Ymin Xmax Ymax
1 ImageA 2 3 12 30
2 ImageB 32 95 48 102
So in this case, I’m trying to filter the rows in ImageA down to include only lines where X is between 2 and 12, and Y is between 3 and 30
$ImageA
X Y CritA CritB
2 10 12 cbra 117
And then ImageB down to only lines where X is between 32 and 48, and Y is between 95 and 102.
$ImageB
X Y CritA CritB
2 35 99 bzt 105
The direction I think this will go is filtering, somehow, using lapply() to iterate through the DFs in df_list. Where I’m stuck is pulling the matching data from filter_coords to filter each of the data frames.
I’ve tried variations of this to try and get started (just filtering for Y for now):
test_filtered <- lapply(df_list, function(x) filter(x, Y > filter_coords$Ymin[x] & Y < filter_coords$Ymax[x]))
And only got errors.
Is this something that’s possible? Do I need to completely reformat my input data? I’m pretty new to R, and while I could do this for my data (~40 image DFs) in Excel, I’m trying to use any excuse to improve my R skills. I’m just at a loss here as nothing I’ve found in my googling has turned up anything I can throw at this.
CLeeSehn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.