2015-11-02 96 views
0

我有一個包含4列的data.frame。第一列是從2015年11月1日至2015年11月30日的the_day。根據amount_raised,接下來的3個值對應於每一天。然而,由於在接下來的3列中沒有值(沒有籌集資金),有些日期不見了。在第二天在R中添加一行,在每一列中添加0

例如,11/3/15丟失。我想要做的是在日期爲11/2/15和11/4/15之間添加一行,在接下來的3列中添加零。因此,它會讀這樣的:

11/3/2015 0 0 0 

我一定要創造一個載體,然後將其添加到現有的data.frame?我覺得必須有一個更快的方法。

+2

請'dput'數據組。 – nrussell

+0

並且期望輸出 – Minnow

+0

結構(列表(the_day = structure(c(16742,16743,16744,16745, 16746,16747),class =「Date」),inf = c(「1.32」,「4.25」,「 3.25「, 」1「,」4.75「,」32「),指定= c(」156「,」40「,」25「,」15「,」10「, 」0「 (「157.32」,「44.25」,「28.25」,「16」,「14.75」,「32」 )),.Names = c(「the_day」,「inf」,「specified」,「both」 row.names = c(NA, 6L),class =「data.frame」) – George

回答

0

這應該工作,

date_seq <- seq(min(df$the_day),max(df$the_day),by = 1) 
rbind(df,cbind(the_day = as.character(date_seq[!date_seq %in% df$the_day]), inf = "0", specified = "0", both = "0")) 

# the_day inf specified both 
# 1 2015-11-02 1.32  156 157.32 
# 2 2015-11-04 4.25  40 44.25 
# 3 2015-11-05 3.25  25 28.25 
# 4 2015-11-06 1  15  16 
# 5 2015-11-07 4.75  10 14.75 
# 6 2015-11-08 32   0  32 
# 7 2015-11-03 0   0  0 

如果你想對它進行排序,根據the_day,參加一個變量的數據幀,並使用order功能

ans <- rbind(df,cbind(the_day = as.character(date_seq[!date_seq %in% df$the_day]), inf = "0", specified = "0", both = "0")) 
ans[order(ans$the_day), ] 

# the_day inf specified both 
# 1 2015-11-02 1.32  156 157.32 
# 7 2015-11-03 0   0  0 
# 2 2015-11-04 4.25  40 44.25 
# 3 2015-11-05 3.25  25 28.25 
# 4 2015-11-06 1  15  16 
# 5 2015-11-07 4.75  10 14.75 
# 6 2015-11-08 32   0  32 
0

data.frames在內部按行處理時效率不高。我會建議沿着以下幾行:

  1. 創建空(零)30x3矩陣。這將包括您的amount_raised。
  2. 創建日期從11/1至11/30
  3. 爲每個現有的日期完整序列,發現它是在比賽的完整序列
  4. 從數據幀複製相應行的匹配行的矩陣(使用match()函數)。
  5. 最終,從新的序列和矩陣中創建一個新的數據幀。
相關問題