Home > Enterprise >  R st_join return polygon with point attributes
R st_join return polygon with point attributes

Time:05-14

Let's say I have the below data along with the code. The code returns point data but I want a polygon.

How can I do a spatial join such that it returns a polygon with both the point and polygon attributes? (Basically, the data will be matched/joined based on the points that fall with in the polygon)

Code Data

library(sf)
library(tidyverse)

# Sample poly
poly =  st_read(system.file("shape/nc.shp", package="sf")) # included with sf package

# Sample points
pts = data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                  x = c(-78.633333, -79.819444, -77.912222),
                  y = c(35.766667, 36.08, 34.223333)) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326) %>% 
  st_transform(st_crs(poly)) 

# Spatial join and output a polygon with the joined attributes, stuck here....
cities_with_counties = st_join(pts,
                                poly)

CodePudding user response:

The geometry type returned by sf::st_join() is driven by the functions first argument.

Consider flipping the two - st_join(poly, pts).

The difference in output should be only in geometry type (and ordering of columns).

  •  Tags:  
  • r sf
  • Related