在 R 中使用 system2() 调用 shp2pgsql

Invoke shp2pgsql using system2() in R

我想编写一个 R 脚本,使用 Bash 中的 shp2pgsql 选项自动将 ESRI 形状文件发送到 PostgreSQL。

# in Bash
shp2pgsql -I -s Port Shapefile schema.table | psql DB

# in R
Command<-c("-I","-s",Port,"shapefile","schema.table","|","psql","DB")
system2("shp2pgsql",Command,wait=FALSE)
/bin/sh: shp2pgsql: command not found
/bin/sh: psql: command not found

# Alternative in R using system
system("shp2pgsql -I -s 4326 shapefile schema.table | psql DB")
/bin/sh: shp2pgsql: command not found
/bin/sh: psql: command not found

*我知道还有其他方法可以达到这个结果,希望得到这方面的答案。但是,我对为什么system2方法不起作用特别感兴趣。

需要改成R内的路径

# Find the correct directory
# Importantly, you do not want "locate psql".
# You want the directory psql is in, i.e., bin, not the full path to psql
Directory<-system("locate bin | grep /Applications/Postgres.app",inter=TRUE)[[1]]

# Create a command to redirect the path
Export<-paste("export PATH=",Directory,":$PATH",sep="")

# Create a command listing your shp2psql command
Command<-"shp2pgsql -I -s 4326 shapefile schema.table | psql DB"

# Join them using && to ensure that Export finishes before executing command
FinalCommand<-paste(Export,"&&",Command,sep=" ")

# Export it to your system
system(FinalCommand)