有没有办法在 R 中调用 PostgreSQL tablefunc 模块?

Is there any way to call PostgreSQL tablefunc module in R?

我想在 R 环境中调用一些 PostgreSQL/PostGIS tablefunc 查询。有什么办法可以做到吗?

例如:

dbGetQuery(con, "SELECT * FROM CROSSTAB(
'SELECT factor1, factor2, ROUND(SUM(ST_AREA(geom))::numeric, 3) FROM table GROUP BY factor1, factor2 ORDER BY 1,2',
'SELECT factor2 FROM table GROUP BY factor2 ORDER BY factor2 '
) AS ct("factor1" varchar, "factor2value1" varchar, "factor2value2" varchar, "factor2value3" varchar)
")

如果您成功连接到 Postgres,任何兼容的 Postgres 查询都可以工作。因此,如果 SQL 语句在 Postgres(即 psql、pgAdmin)中工作,它应该在连接到它的客户端(如 R)中工作。注意:crosstab 需要扩展名。只需使用反斜杠转义 SQL 语句中的双引号即可编译为 R:

中的字符
sql <- "SELECT * 
        FROM CROSSTAB(
           'SELECT factor1, factor2, 
                   ROUND(SUM(ST_AREA(geom))::numeric, 3) 
            FROM table 
            GROUP BY factor1, factor2 
            ORDER BY 1,2'
           ,
           'SELECT factor2 
            FROM table 
            GROUP BY factor2 
            ORDER BY factor2 '
         ) AS ct(\"factor1\" varchar, \"factor2value1\" varchar,
                 \"factor2value2\" varchar, \"factor2value3\" varchar)"

dbGetQuery(con, sql)