Search code examples
rdataframerastershapefile

How to load multiple shapefile of point and convert it into csv file in loops?


I want to read and convert multiple shapefile into csv. The link contain sample of shapefile. Following is the code I was trying.

  library(raster)
  setwd("D:/share_1/PAPER_regimes/22_06_22/hp/firepoint_12_veg")
  all.files <- list.files(pattern="\\.shp$")
  out.files <- gsub("\\.shp$", ".csv")
  crs <- CRS("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0")
  for(i in 1:length(all.files)) {
   d <- readOGR(all.files[i], stringsAsFactors = FALSE)
   sp <- SpatialPointsDataFrame(coords = d[c("Longitude", "Latitude")], d, proj4string = crs) 
   utm <- spTransform(sp, CRS("+proj=utm +zone=16 +datum=WGS84"))
   shapefile(utm, out.files[i])
    }

link contain few shapefile and dataset which are in point


Solution

  • You can do that like this

    library(terra)
    all.files <- list.files(pattern="\\.shp$", full=TRUE)
    out.files <- gsub("\\.shp$", ".csv", all.files)
    
    for(i in 1:length(all.files)) {
       d <- vect(all.files[i])
       utm <- project(d, "+proj=utm +zone=16 +datum=WGS84")
       xy <- crds(utm)
       write.csv(xy, out.files[i], row.names=FALSE)
    }
    

    I do not know why you went to the lon/lat in the attributes, but if that is what you need you can do:

    for(i in 1:length(all.files)) {
       d <- vect(all.files[i])
       geo <- vect(data.frame(d), c("LONGITUDE", "LATITUDE"), crs="+proj=longlat")
       utm <- project(d, "+proj=utm +zone=16 +datum=WGS84")
       xy <- crds(utm)
       write.csv(xy, out.files[i], row.names=FALSE)
    }