使用R中的system2()调用shp2pgsql

时间:2017-03-02 17:24:40

标签: r bash postgresql postgis

我想编写一个R脚本,它将使用Bash中的shp2pgsql选项自动将ESRI shapefile发送到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方法不起作用的原因。

1 个答案:

答案 0 :(得分:1)

需要更改为

中的路径
# 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)