'st_join(..., join = st_within) inserts columns with NA row values instead of actual values

I have two datasets (sf-objects). Spatial_locations contains the POINT locations where camera's were deployed. MD_full_st1 contains POLYGONS that correspond to a certain habitat type.

Now, I wish to expand the spatial_locations sf data frame with two new columns that represent 1) in which POLYGON the POINT falls, 2) the Habitat of that POLYGON.

I tried using st_join() to join values from columns "polygon-Id" and "habitat" from MD_full_st1 to Spatial_locations. Note values should be added to Spatial_locations only if that POINT is within a certain POLYGON.

Code

#load spatial_locations with crs set to crs of MD_full_st 
spatial_locations <- + st_as_sf(cov,coords=c("deploymentLongitude","deploymentLatitude"), crs = + st_crs(MD_full_st))

# include only columns with polygon Id and habitat type #
MD_full_st1 <- MD_full_st[,c("Id", "habitat")]

# assign polygon Id and habitat type to POINTS #
loc_in_MD <- st_join(spatial_locations, MD_full_st1, join = st_within)

expected output: - new sf object loc_in_MD with columns "Id" and "habitat"; column values Id-numbers of polygons and habitat types.

output: - new sf object loc_in_MD with columns "Id" and "habitat"; column values are all NA

I beleive the coordinates of my POLYGONS and POINTS do not match and that's why st_join does not find any POINT within a POLYGON. However I made sure to use the exact same CRS.



Solution 1:[1]

You need to set largest=TRUE in st_join.

loc_in_MD <- st_join(spatial_locations, MD_full_st1, join = st_within, largest = TRUE)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Casey Slaught