2012-07-05 20 views
0

可以說,我有一個數據集,在我經歷過幾天的時候,行數不斷下降,我想再次添加這些行。R代碼 - 巧妙的循環來添加行

示例缺少行:

Fruits <- c(rep(c("apples","oranges","pears","kiwis"),3), 
    "bananas","oranges","pears","kiwis","bananas","pears","kiwis","bananas") 
Days <- c(rep("Monday",4),rep("Tuesday",4),rep("Wednesday",5), 
    rep("Thursday",4),rep("Friday",3)) 
Amounts <- c(10,15,20,20,10,15,20,20,10,15,20,20,25,15,20,20,25,20,20,25) 
dfmissing <- data.frame(Fruits,Days,Amounts) 

而且我希望它填補在週四和週五新行時,「蘋果」和「橘子」輟學如此。

請注意,「香蕉」星期三首次出現,這使事情稍微複雜化。

完成的表格應類似於以下

Fruits <- c(rep(c("apples","oranges","pears","kiwis"),2), 
    rep(c("apples","oranges","pears","kiwis","bananas"),3)) 
Days <- c(rep("Monday",4),rep("Tuesday",4), 
    rep("Wednesday",5),rep("Thursday",5),rep("Friday",5)) 
Amounts <- c(rep(c("10","15","20","20"),2),rep(c("10","15","20","20","25"),3)) 
dfcomplete <- data.frame(Fruits,Days,Amounts) 

兩個表比較

dfmissing 
dfcomplete 

假設只有一個數據的一週有那麼「星期一」永遠不會被重複等 - 列「天「是一個獨特因素的列表。

在此先感謝。

+0

你想填補缺失的行什麼? 「NA」還是有些價值? – mnel

+0

該行的最後一個值(如在dfcomplete中) – lilster

回答

1

這裏我的快速慢循環嘗試。用你所描述的,我用了兩個if語句,一個用來檢查是否有新的水果添加,另一個用來檢查是否有任何缺失的水果。這不是非常有效,但它會完成工作。我會讓你理清data.frame。

# Get what days are in the data frame 
days <- unique(dfmissing$Days) 
# Start with the first day to get the fruits. 
fruit <- dfmissing[dfmissing$Days==days[1],"Fruits"] 
# Create a loop to loop over the actual days 
for(i in 2:length(days)){ 
    # Determine which fruits are present on this day. 
    newdayfruit <- dfmissing[dfmissing$Days==days[i],"Fruits"] 

    newFruitToAdd <- newdayfruit[is.na(match(newdayfruit,fruit))] 
    # Check if there are any new fruits to add. 
    if(length(newFruitToAdd)>0){ 
     # Add the new fruit to the fruits. 
     fruit <- c(as.character(fruit), as.character(newFruitToAdd)) 
    } 
    # Check if there are any missing fruits. 
    missingFruit <- fruit[is.na(match(fruit, dfmissing[dfmissing$Days==days[i],"Fruits"]))] 
    # If there are missing fruits then the should be added to the dataframe 
    if(length(missingFruit)>0){ 
     # Loop over each missing fruit. 
     for(j in 1:length(missingFruit)){ 
      # Get the value of the missing fruit from the previous day 
      updateWith <- dfmissing[dfmissing$Days==days[i-1]&dfmissing$Fruits==missingFruit[j],] 
      # Change the day to the current day 
      updateWith$Days <- days[i] 
      # Add a row to the data frame with the updated value. 
      dfmissing <- rbind(dfmissing, updateWith) 
     } 
    } 
} 
+0

非常感謝。非常感激。 – lilster