【问题标题】:R - appending rows to data frame in a for loop?R - 在for循环中将行附加到数据帧?
【发布时间】:2017-10-21 02:54:47
【问题描述】:

我认为这是一个愚蠢的问题,但我仍然需要一些语法帮助,因为我是 R 新手。

我有一个包含 5 列的空白数据框。对于每一行,pgsql 查询获取一行 5 个值,这些值需要在循环的每次迭代中添加到数据帧中。

Exiting_df:

Mat  CrA  Cur  Dil  Ccl
NA   Na    Na   Na   Na

循环的每次迭代都会从 pgsql 查询中带来一个新的值数据框,如下所示:

Mat  CrA  Cur  Dil  Ccl
5    13    9   44   2

这将像这样附加到 Existing_df: 在 i = 1:

Mat  CrA  Cur  Dil  Ccl
5    13    9   44   2

在 i=2 时:

Mat  CrA  Cur  Dil  Ccl
5    13   9    44   2
11   1    113  41   11

在 i=3:

Mat  CrA  Cur  Dil  Ccl
5    13   9    44   2
11   1    113  39   11
14   22   79   54   12

等等..

这是for循环:

for (i in 1:nrow(month_stats))
{
status_counts <- tbl(con_cg_db,sql(
paste("select distinct stagename,
       sum(case when stagename is not null then 1 else 0 end)
       from current_oppty_sf 
       where extract(month from cast(loan_agreement_date__c as date)) = ",i,"
       group by stagename",sep="")
))
status_counts<- t(as.data.frame(status_counts))
### something needs to go here to appropriately combine the data
###frames as I've described in my question
}

有时,根据数据,从 pgsql 查询中获取值的数据框只有 3 或 4 列。在这种情况下,缺少的列需要在主数据框的相应行和列自动占用 0。

我该怎么做?

【问题讨论】:

  • 你能在答案中举一个简单的例子吗?
  • 考虑先搜索 SO。这方面的例子有几十个。试试[r] do.call rbind

标签: r for-loop dataframe append


【解决方案1】:
require(dplyr)

df<- c() 

for (i in 1:nrow(month_stats))
    {
    status_counts <- tbl(con_cg_db,sql(
    paste("select distinct stagename,
           sum(case when stagename is not null then 1 else 0 end)
           from current_oppty_sf 
           where extract(month from cast(loan_agreement_date__c as date)) = ",i,"
           group by stagename",sep="")
    ))
    status_counts<- t(as.data.frame(status_counts))
    df <- bind_rows(df, status_counts)
    }

当缺少某些值时,此代码将为您提供 NA 而不是零。如果你真的想要零,你可以在循环之后插入它们:

df[is.na(df)] <- 0

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 2015-04-05
    • 2016-01-31
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2021-10-03
    • 2015-06-06
    相关资源
    最近更新 更多