如何在 R 中将 csv 转换为 shp

How to convert csv to shp in R

过去几天我一直在尝试将 csv 转换为 shapefile。我知道我可以在 QGIS 或 Arc 中轻松完成,但想将此过程添加到我现有的 R 代码中。

所以我可以毫无问题地读取 csv

MyData <- read.csv(file="c:/TheDataIWantToReadIn.csv", header=TRUE, sep=",")

我从 Packages Shapefile 帮助指南中找到了下面的代码。但是我似乎无法找到一种方法让它在我的代码上工作。我的每一行都是一个点,因此我尝试创建的 shapefile 将是所有点。我没有 Id 列,但是我在两个单独的列中有 x 和 y 数据。

dd <- data.frame(Id=c(1,2),X=c(3,5),Y=c(9,6))
ddTable <- data.frame(Id=c(1,2),Name=c("Item1","Item2"))
ddShapefile <- convert.to.shapefile(dd, ddTable, "Id", 1)
write.shapefile(ddShapefile, "c:/test", arcgis=T)

如有任何帮助,我们将不胜感激。

我建议使用 rgdal 而不是 shapefiles。要使用 rgdal,您必须查看 http://cran.revolutionanalytics.com/web/packages/rgdal/ 的系统要求。

下面的代码应该能让您朝着正确的方向前进:

install.packages(c("rgdal", "sp"))
library(rgdal)
library(sp)
MyData <- read.csv(file="c:/TheDataIWantToReadIn.csv", header=TRUE, sep=",")

以下代码片段来自Mapping in R using the ggplot2 package.

class(MyData) # data.frame
coordinates(MyData)<-~longitude+latitude # whatever the equivalent is in your 
# data.frame
class(MyData) # [1] "SpatialPointsDataFrame"
          # attr(,"package")
          # [1] "sp"

以下代码片段来自How to write a shapefile with projection - problem solved

writeOGR(crest.sp, "c:/test", "layer name", driver = "ESRI Shapefile")

我认为这会使用 sf 包将 CSV 文件转换为 shapefile:

setwd('C:/Users/mark_/Documents/ctmm/density_in_R')

library(sf)

# Create lat-long data
set.seed(1234)

# 21.4389° N, 158.0001° W
longitude <- rnorm(1000, mean = 0, sd = 1) + -158.0
latitude  <- rnorm(1000, mean = 0, sd = 1) +   21.4
timestamp <- as.POSIXct("2021-06-24 10:30:05", format="%Y-%m-%d %H:%M:%S", tz="UTC")
my.data <- data.frame(longitude, latitude, timestamp)
head(my.data)
write.csv(my.data, "fake_lat_long_points_oahu.csv", row.names = FALSE, quote = FALSE)

# fake lat-long data imported from CSV file
oahu.lat.long <- read.csv("fake_lat_long_points_oahu.csv", header = TRUE, 
                           stringsAsFactors = FALSE, na.strings = "NA")

head(oahu.lat.long)

# Code in the following section based on:
# https://www.gisnote.com/2020/11/23/csv-to-shapefile-in-r/
# https://erinbecker.github.io/r-raster-vector-geospatial/10-vector-csv-to-shapefile-in-r/index.html

# Define coordinate reference system
prj4string <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
my.projection <- st_crs(prj4string)

# Create sf object
oahu_lat_long_sf <- st_as_sf(oahu.lat.long, coords = c("longitude", "latitude"), crs = my.projection)
st_crs(oahu_lat_long_sf)

plot(oahu_lat_long_sf)

# Export shapefile
st_write(oahu_lat_long_sf, "C:/Users/mark_/Documents/ctmm/density_in_R/fake_oahu_lat_long_sf_June24_2021/oahu_lat_long_sf.shp", driver="ESRI Shapefile")

这是将 shapefile 导入 QGIS 并添加底图后的屏幕截图: