Search code examples
rgeospatial

Overlay values corresponding lat and long in a shape file in R


I want to overlay lat-long corresponding wmo points from excel over shapefile in R. I went through others' problems, but still, I am unable to do it. I have tried this code but not working. Please help.

shapestate <- read_sf(file.path(dir_ls$input_dir, 'shapefile'), 'State_sim')
plot(st_geometry(shapestate), col="darkblue", main="Tahoe HUC8", axes=TRUE)

wmo<-read.xlsx(file.path(dir_ls$input_dir, 'cyclone', 'checking wind speed.xlsx'))

coordinates(wmo) <- ~ LAT + LON
IND<-spTransform(shapestate, CRS("+proj=longlat +ellps=WGS84 +datum=WGS84"))


points(wmo$LAT ~ wmo$LON, col = "red", cex = 1, pch = 19)

The shapefile and values corresponding lat-long in excel are shared in this given link. shapefile and wmo values in excel


Solution

  • Let me help you. As the shp file alone is not enough to read it properly, I will use geodata package to read the boundaries. In your case:

    sf::st_read("path_to_shapefile.shp") |>
      sf::st_geometry() |>
      plot()
    

    should be enough.

    With sf package and its functions:

    geodata::gadm("India", path = tempdir()) |>
      sf::st_as_sf() |>
      sf::st_geometry() |>
      plot()
    
    readxl::read_excel("/home/sapi/Downloads/checking wind speed.xlsx") |>
      sf::st_as_sf(coords = c("LON", "LAT"), crs = 4326) |>
      sf::st_geometry() |>
      plot(pch = 16, col = "red", add = TRUE)
    

    Or with terra package:

    geodata::gadm("India", path = tempdir()) |>
      terra::plot()
    
    readxl::read_excel("/home/sapi/Downloads/checking wind speed.xlsx") |>
      terra::vect(geom = c("LON", "LAT"), crs = "EPSG:4326") |>
      terra::plot(pch = 16, col = "red", add = TRUE)
    

    Please have a look on sf::st_read() and/or terra::vect() functions to read your shapefile.

    Created on 2022-10-13 with reprex v2.0.2