R – How to Select Nearest Feature to a Point by Selected Column

rsf

I'm using crs= 2263. I have two datasets, buildings and 311. I would like to see what is the closest building to each 311 complaint.

st_nearest_feature(311, Buildings) 

I believe this works but it gives me the row number. I would like it to give me the building name from column in Buildings called "Name"

Best Answer

You need to get the Name column from Buildings and extract the matching record by index number:

Buildings$Name[st_nearest_feature(my311, Buildings)]

This is standard R subsetting of data frames, nothing specially spatial here, and should be covered in any good R introduction, where you'll learn all sorts of other tricks for working with data frames.

You could even do it in two steps if you might want to use the matching row again:

nearest_311 = st_nearest_feature(my311, Buildings)
name_of_nearest = Buildings$Name[nearest_311]

Note that 311 is probably not a good name to give your data, so I've called it my311. Have you really called it 311? Because it helps if your questions use real data names and examples.

Related Question