runiquedistinctr-sf

Return complete cases of sf object in R


What is the equivalent of df <- df[complete.cases(df), ] for sf objects?

I know sf objects behave mostly like dataframes with a "sticky" geometry column, but running the above code returns the following error:

df <- df[complete.cases(df), ]

Error in complete.cases(df) : invalid 'type' (list) of argument

This is likely due to sf objects storing their geometry variables as lists. Your input is appreciated!


Solution

  • You can use sf::st_is_empty() to check for empty geometries

    library(sf)
    
    pt1 <- sf::st_sfc(sf::st_point())
    pt2 <- sf::st_sfc(sf::st_point(c(0,0)))
    
    sf <- sf::st_sf(geometry = c(pt1, pt2))
    
    sf[!sf::st_is_empty(sf), ]
    
    # imple feature collection with 1 feature and 0 fields
    # geometry type:  POINT
    # dimension:      XY
    # bbox:           xmin: 0 ymin: 0 xmax: 0 ymax: 0
    # epsg (SRID):    NA
    # proj4string:    NA
    # geometry
    # 1 POINT (0 0)