-1

I am trying to use a dataframe and the sf library to take some coordinates from a list of events and turn it into a shapefile to map. Some of the rows are missing lat/long and when I am using the st_as_sf function, it fails because of missing coords. The data comes from an external source in csv, and though I tried to trim rows missing info (going to sql and back to csv) the formatting of the document seems to be inconsistent so it shifts some rows and I have the same problem. Is there anyway in r to either trim the dataframe where it is missing specific columns (lat, long) or when creating the dataframe to omit those columns? I guess I can probably loop through and check as necessary, but wondering if there is a better way? Thanks!

nick
  • 789
  • 1
  • 11
  • 27
  • 1
    A simple dplyr-filter(), or subset on the data.frame with spatial info will probably do the trick, like `world.map <- world.map[!is.na(world.map@data$latitude), ]`. If you have got more specific quenstions; please add some code + sample data to your post. – Wimpel Jun 13 '18 at 18:23
  • When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jun 13 '18 at 18:34
  • True, but if I knew what I was trying to do I wouldn't need to ask this time, I could've posted some code but the only relevant bit is that I have a dataframe and I need the next line. – nick Jun 13 '18 at 19:21

1 Answers1

1

Let's say you have a data frame and the coordinates are stored in columns called 'lat' and 'lng'.

df <- data.frame(lat = c(NA, 2, 2), lng = c(NA, 1, NA))

Filter out any missing coordinates:

df <- df[which(!is.na(df$lat) & !is.na(df$lng)),]

Convert to sf:

sf.df <- st_as_sf(df, coords = c('lat', 'lng'))

You should also set the projection of your data using the crs argument within st_as_sf()

sebdalgarno
  • 2,929
  • 12
  • 28