how to make a data frame into a simple features data frame?

前端 未结 2 1213
栀梦
栀梦 2020-12-16 19:05

I\'ve got a table with place references and x and y coordinates in a given coordinate reference system. I want to turn that into a simple features data frame. How can I crea

相关标签:
2条回答
  • 2020-12-16 19:46

    Your attempt and the accepted answers are unnecessarily complicated and terribly confusing. Just go with st_as_sf (which by the way also easily migrates all objects from the outdated sp class (SpatialPolygonsDataFrames and the like)):

    df <- data.frame(place = "London", 
           lat = 51.5074, lon = 0.1278,
           population = 8500000) # just to add some value that is plotable
    projcrs <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
    df <- st_as_sf(x = df,                         
               coords = c("lon", "lat"),
               crs = projcrs)
    

    And we are done, as easy as that.

    Just to visualise it:

    library(tmap)
    data("World")    
    tm_shape(World[World$iso_a3 == "GBR", ]) + tm_polygons("pop_est") + 
        tm_shape(df) + tm_bubbles("population")
    

    Or with the new amazing geom_sf from ggplot2:

    library(ggplot2)
    ggplot(World) + geom_sf() + geom_sf(data = df, shape = 4, col = "red", size = 5)
    

    0 讨论(0)
  • 2020-12-16 19:54

    UPDATE The answer from @Franz Plumpton is the correct correct solution with a single epsg. My answer below is only necessary when each row of a data.frame has a different epsg. Otherwise, this would be a duplicate (as pointed out by @Henrik above).

    library(sf)
    library(tibble)
    
    df <- data_frame(place = c("London", "Kalamazoo"), 
               lat = c(51.5074, 396088), lon = c(0.1278, 5452158),
               epsg = c(4326, 32610))
    
    l <- lapply(unique(df$place), function(x){
      df <- df[df$place == x,]
      epsg <- df$epsg[1]
      df  <-  st_as_sf(df, coords = c('lon', 'lat'), crs = epsg)
    }) 
    

    you could then transform all to the same epsg and combine into a single data.frame:

    do.call(rbind, lapply(l, function(x) x <- st_transform(x, 4326)))
    
    0 讨论(0)
提交回复
热议问题