Home > Back-end >  How filter specific rows in a df
How filter specific rows in a df

Time:02-11

I want to select each row which have a list values in a geometry column.

Some rows have a empty list and I want to remove them and just get the rows with a list of geometry values...

I can do that with numeric values with dplyr::filter but I don't know do that with a list...

Someone can help me please ?

CodePudding user response:

Without your data it will be hard to exactly answer your question, and depending on if your list element is NA, NULL, or length 0 (i.e., character(0), integer(0)). A couple of options you could try:

# List with both NA and NULL values
lst <- list(c(1:5), c(LETTERS[1:18]), c(NA), c(NULL), integer(), character() ,c(1:17))

# Remove if list element is NULL
plyr::compact(lst)

# Remove if list element is NA
Filter(Negate(anyNA), lst)

# If element is zero length as character(0), integer(0) 
lst[lapply(lst, length) > 0]

CodePudding user response:

Sorry but my dataset is really heavy so I just give you an example with a basic shapefile that you can find here : https://filesender.renater.fr/?s=download&token=190c5a7e-5572-4a47-a2d1-37b7004aa9b5

Then here is my code:

library(sf)
library(terra)
library(mapview)
library(dplyr)

shp = st_read("path_to_my_shp")
shp = st_transform(shp, crs=2309)
vect_dist = c(1000, 2500, 5000, 100000)
test_buff = NULL

for (i in vect_dist){
  res = st_buffer(x = shp , dist = (-1*i))
  res$DIST = i 
  test_buff = rbind(test_buff, res)
} 

I'm actually looking to do internal buffers on polygons with different distances. It works well but for some polygons, the buffers are too big (like in the examples for 100000 meters) and I get an empty list in the geometry column of my dataframe. I just try to do my loop to get all the geometries and then remove the empty geometries corresponding to list().

  • Related