ReginaldMilton
ReginaldMilton

Reputation: 309

Conditionally remove items from a list in R

I know there are many similar questions about removing items from a list, but I've been unable to solve my problem in particular - and I appreciate the help.

Simply put, I'd like to remove any entry (row) that has a value that is greater than -74.

list(structure(c(40.7571907043457, 40.7601699829102, 40.761848449707, 
40.7660789489746, -73.9972381591797, -74.0038146972656, -74.0072479248047, 
-74.0172576904297), .Dim = c(4L, 2L), .Dimnames = list(c("1", 
"2", "3", "4"), c("lat", "lon"))), structure(c(40.7582893371582, 
40.760498046875, 40.7620582580566, 40.7662887573242, -73.9975280761719, 
-74.0031967163086, -74.0070190429688, -74.0170593261719), .Dim = c(4L, 
2L), .Dimnames = list(c("1", "2", "3", "4"), c("lat", "lon"))))

Thanks so much.

Upvotes: 0

Views: 556

Answers (1)

Sotos
Sotos

Reputation: 51582

If you only need to look at lon column with the negative values then simply,

lapply(your_list, function(i)i[i[,2] <= -74,])

In case you want to check both columns,

lapply(your_list, function(i)i[rowSums(i<=-74) > 0, , drop = FALSE])

Both give the same result,

[[1]]
       lat       lon
2 40.76017 -74.00381
3 40.76185 -74.00725
4 40.76608 -74.01726

[[2]]
       lat       lon
2 40.76050 -74.00320
3 40.76206 -74.00702
4 40.76629 -74.01706

Upvotes: 2

Related Questions