2016-11-30 40 views
0

我有一個名爲的數據幀BalticRainfallDuration。數據框的一小部分如下所示。如何總結數據幀中列的特定單元

"TIMESTAMP"  "Rainfall" "Duration" 
2014-03-19 10:40:00  0.508 0 
2014-03-19 10:50:00  1.016 10 
2014-03-19 11:00:00  0.254 10 
2014-03-24 09:10:00  0.254 7090 
2014-03-26 12:40:00  0.254 3090 
2014-03-27 11:50:00  0.254 1390 
2014-03-27 12:20:00  0.254 30 
2014-03-28 14:30:00  0.254 1570 
2014-03-28 14:40:00  0.508 10 
2014-03-28 14:50:00  0.508 10 
2014-03-28 15:00:00  0.254 10 
2014-03-28 15:10:00  0.508 10 
2014-03-28 15:20:00  0.254 10 
2014-03-28 15:40:00  0.254 20 
2014-03-29 13:00:00  0.254 1280 

對於TIMESTAMP中持續10分鐘降雨的每個事件,我想總結這些相應事件的「持續時間」。輸出數據幀「Event_Duration」應該如下:

"TIMESTAMP"  "Rainfall"  "Duration" "Duration_sum" 
2014-03-19 10:40:00  0.508    0  
2014-03-19 10:50:00  1.016   10   20   
2014-03-19 11:00:00  0.254   10 
2014-03-24 09:10:00  0.254   7090   NA 
2014-03-26 12:40:00  0.254   3090   NA 
2014-03-27 11:50:00  0.254   1390   NA 
2014-03-27 12:20:00  0.254   30   NA 
2014-03-28 14:30:00  0.254   1570   NA 
2014-03-28 14:40:00  0.508   10  
2014-03-28 14:50:00  0.508   10  
2014-03-28 15:00:00  0.254   10   50 
2014-03-28 15:10:00  0.508   10  
2014-03-28 15:20:00  0.254   10 
2014-03-28 15:40:00  0.254   20   NA 
2014-03-29 13:00:00  0.254   1280   NA 

這意味着有2個連續10分鐘的持續時間降雨事件。活動1是20分鐘,活動2是50分鐘。

我嘗試以下的代碼:

Event_Duration<-with(BalticRainfallDuraiton,diff(BalticRainfallDuraiton$TIMESTAMP)==10, sum(BalticRainfallDuraiton$Duration)) 

Duration_Sum<-data.frame(cbind(BalticRainfallDuration,Event_Duration)) 

但在輸出我只接收TRUE或FALSE的結果,而不是持續時間之和的值。 我將非常感謝,如果有人可以通過建議更正我的代碼或提供替代代碼來幫助我。

+0

'20'和'50'應該在阿塔右下方一排? –

+0

20和50的位置並不重要,只要這些是每個降雨事件的持續時間累計總和 – Sami

回答

0

如何:

library(dplyr) 
df <- df %>% 
    mutate(grp = ifelse(Duration > 10, 1, 0)) %>% 
    mutate(grp = cumsum(grp)) %>% 
    group_by(grp) %>% 
    mutate(Duration_sum = c(rep(NA, n() - 1), sum(Duration) - Duration[1])) %>% 
    ungroup() %>% 
    mutate(grp = NULL) 

其中給出:

> df 
# A tibble: 15 × 4 
      TIMESTAMP Rainfall Duration Duration_sum 
       <dttm> <dbl> <int>  <int> 
1 2014-03-19 10:40:00 0.508  0   NA 
2 2014-03-19 10:50:00 1.016  10   NA 
3 2014-03-19 11:00:00 0.254  10   20 
4 2014-03-24 09:10:00 0.254  7090   0 
5 2014-03-26 12:40:00 0.254  3090   0 
6 2014-03-27 11:50:00 0.254  1390   0 
7 2014-03-27 12:20:00 0.254  30   0 
8 2014-03-28 14:30:00 0.254  1570   NA 
9 2014-03-28 14:40:00 0.508  10   NA 
10 2014-03-28 14:50:00 0.508  10   NA 
11 2014-03-28 15:00:00 0.254  10   NA 
12 2014-03-28 15:10:00 0.508  10   NA 
13 2014-03-28 15:20:00 0.254  10   50 
14 2014-03-28 15:40:00 0.254  20   0 
15 2014-03-29 13:00:00 0.254  1280   0 

在這裏有幾個步驟,可能沒有必要,這取決於你具體是怎麼想輸出的樣子。同樣,您可能希望擺脫零持續時間值(最後一步是額外的mutate步驟)。

+0

非常感謝!它工作得很好:) – Sami

+0

不客氣,我很高興它幫助。 – rosscova