【问题标题】:Understand lists structure了解列表结构
【发布时间】:2018-10-23 09:59:55
【问题描述】:

我有连接到我的 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。

【问题讨论】:

  • x 是列名,1 是行号。
  • 但是当我对 res 中的元素执行 typeof(x) 时,它会显示“list”。列表怎么会有列号和行号?
  • 因为你有一个数据框列表。您可以使用here 方法将数据帧列表转换为单个数据帧,也可以使用dplyr/purrr
  • 提前致谢。由于我不了解它的结构,因此无法正常使用 Google 搜索。

标签: r list transform


【解决方案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)

【讨论】:

  • 非常感谢,正是我正在寻找的。伙计,我真的忘记了我声明中的那个 x - Flüchtigkeitsfehler,Oliver! :-) 丹克!
  • 很高兴能够提供帮助!如果你不介意,Bitte 接受 Antwort ;-)
  • 嗨,一个小问题。结果看起来令人满意,但表名不是“真正的”列——它们没有名称。这变得有问题,因为当我使用带有 sqldf 的新表(我将 do.call() 的结果保存到 res_2 中)并在其上使用 select * 时,它只给了我布尔列“x”,而不是表名柱子。任何的想法? :-)
  • 您可以使用 colnames(res_2) &lt;- 'x' 重命名数据框的列(这将使列名称为 x 您可以随意命名)。
  • @JohnnyBanana,我编辑了答案,看看是否有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 2020-05-10
  • 2016-04-27
  • 2019-01-08
  • 2021-02-27
  • 2015-12-27
  • 2015-12-25
相关资源
最近更新 更多