我想在一堆表,列和db schemata上运行相同的SQL。我有一个与此类似的数据框:
schema <- c('schema_1','schema_1','schema_1', 'schema_2', 'schema_2')
table <- c('table_1','table_1','table_2', 'table_3', 'table_3')
column <- c('A','B','V','X','Y')
df <- data.frame(schema, table, column)
我想在df的所有行上运行一个像这样的列的第一行的简单SQL:
库(postGIStools)
get_postgis_query(con_ent_gis, "select column from schema.table LIMIT 6")
据我所知,我可以写类似的东西
get_postgis_query(con_ent_gis, "select df$column[i] from df$schema[i].df$table[i] LIMIT 6")
在一个for循环中,怀特?或者任何包或函数是否适用,lapply ..做类似的事情,而不需要循环?
只需使用paste
(或其非空间包装器,paste0
)来构建SQL语句的向量,因为所有对象都是相同的长度。然后,将向量传递给lapply
,以便对返回的对象列表进行迭代查询调用。
# BUILD VECTOR OF SQL STATEMENTS
sqls <- paste0("select ", df$column, " from ", df$schema, ".", df$table, " LIMIT 6")
sqls
# [1] "select A from schema_1.table_1 LIMIT 6"
# [2] "select B from schema_1.table_1 LIMIT 6"
# [3] "select V from schema_1.table_2 LIMIT 6"
# [4] "select X from schema_2.table_3 LIMIT 6"
# [5] "select Y from schema_2.table_3 LIMIT 6"
# ITERATIVELY RUN EACH QUERY TO RETURN LIST OF OBJECTS
data_list <- lapply(sqls, function(s) get_postgis_query(con_ent_gis, s))