了解清单结构

时间:2018-10-23 09:59:55

标签: r list transform

我有连接到PostgresDB的R代码。

它为我的每张表提供了精确的一行,其中一列为布尔类型

res <- lapply(all_tables,
              function(table){
                sqlStatement <- 
                  paste("SELECT CASE WHEN MAX(date) = current_date-1 then TRUE else FALSE end as x from "
                        ,table)
                dbGetQuery(con, sqlStatement)
              })
names(res) <- all_tables
res

结果有些令人满意:

datawarehouse.table1
     x
1 TRUE

datawarehouse.table2
      x
1 FALSE

datawarehouse.table3
      x
1 FALSE

我真正需要的是这样的数据框:

table                  valid
datawarehouse.table1   TRUE
....

我不明白的是那些x和那些1。

1 个答案:

答案 0 :(得分:1)

正如slackline所指出的,1是行号。 x是由于您执行了以下SQL语句:

SELECT CASE WHEN MAX(date) = current_date-1 then TRUE else FALSE end as x from table

您看到那里的as x吗?这就是您要寻找的x

您可以将结果(一个数据框列表)转换为一个数据框,如下所示:

# this is the `res` from your example, with some example data
res <- list("datawarehouse.table1" = data.frame("x" = c(TRUE)),
            "datawarehouse.table2" = data.frame("x" = c(FALSE)),
            "datawarehouse.table3" = data.frame("x" = c(TRUE)))

# the names of the list items should be the values in the new column
table_names <- list("table" = names(res))

res <- do.call(rbind, res)
# get rid of the row names, will have integer indexes instead
rownames(res) <- NULL

# add a new column with the table names
# you could use stringr::str_extract to only pull out the portion you need
res<- cbind(res, table_names)