2017-05-21 72 views
0

我認爲這是一個愚蠢的問題,但仍然需要語法幫助,因爲我是R新手。R - 將行附加到for循環中的數據框?

我有一個空白的數據框,有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像這樣= 1:

Mat CrA Cur Dil Ccl 
5 13 9 44 2 

at 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。

我該怎麼做?

+0

你能舉個簡單的例子嗎? –

+0

首先考慮搜索。這有幾十個例子。嘗試'[r] do.call rbind'。 –

回答

0
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) 
    } 

而不是零,這段代碼會給你一些缺少值的情況。如果你真的想要零,你可以在循環後插入它們:

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