代码之家  ›  专栏  ›  技术社区  ›  N.Varela

R: 如何使用数据帧中的表、列和模式名构建get_postgis_查询?

  •  0
  • N.Varela  · 技术社区  · 6 年前

    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,列的第一行如下:

    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")
    

    在一个循环中,赖特?或者做任何适用的包装或功能。。做一些类似的事情,不需要循环?

    0 回复  |  直到 6 年前
        1
  •  2
  •   Parfait    6 年前

    简单使用 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))