該data frame說我有如下所示作業:
yyyy mm dd hour
2011 5 1 10
2011 5 1 12
2011 5 1 13
2011 5 1 14
2011 5 1 15
2011 5 1 16
2011 5 1 17
2011 5 1 20
2011 5 2 11
2011 5 2 12
2011 5 2 13
2011 5 2 14
2011 5 2 15
2011 5 2 16
2011 5 2 17
2011 5 2 18
2011 5 3 10
[...]
我想添加一個報告連續小時數的新列,如下所示:
yyyy mm dd hour event
2011 5 1 10 1
2011 5 1 12 6
2011 5 1 13 6
2011 5 1 14 6
2011 5 1 15 6
2011 5 1 16 6
2011 5 1 17 6
2011 5 1 20 1
2011 5 2 11 8
2011 5 2 12 8
2011 5 2 13 8
2011 5 2 14 8
2011 5 2 15 8
2011 5 2 16 8
2011 5 2 17 8
2011 5 2 18 8
2011 5 3 10 1
[...]
引數的連續值 ( [mm], [dd])的數量hours由event列 ( [mm] [dd]) 中的值報告。
有什么建議嗎?
uj5u.com熱心網友回復:
下面的兩個基本 R 解決方案都是cumsum/ave解決方案。在Wimpel對該問題的評論之后,有 2 個解決方案。
1.
如果事件不能跨越多天。
i <- c(0, abs(diff(df1$hour)) != 1)
ave(cumsum(i), cumsum(i), FUN = length)
# [1] 1 6 6 6 6 6 6 1 8 8 8 8 8 8 8 8 1
2.
如果事件可以跨越多天。
h <- with(df1, ISOdatetime(yyyy, mm, dd, hour, 0L, 0L))
j <- c(0, abs(diff(h)) != 1)
ave(cumsum(j), cumsum(j), FUN = length)
# [1] 1 6 6 6 6 6 6 1 8 8 8 8 8 8 8 8 1
并將結果分配給ave新列。
df1$event <- ave(<as above>)
資料
df1 <-
structure(list(yyyy = c(2011L, 2011L, 2011L, 2011L, 2011L, 2011L,
2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L,
2011L, 2011L), mm = c(5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L), dd = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L), hour = c(10L, 12L, 13L,
14L, 15L, 16L, 17L, 20L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L,
10L)), class = "data.frame", row.names = c(NA, -17L))
uj5u.com熱心網友回復:
這是一個dplyr解決方案:
df %>%
group_by(yyyy,mm,dd) %>%
mutate(event = ifelse(hour == lead(hour) -1 | hour == lag(hour) 1,1,0)) %>%
mutate(event = ifelse(is.na(event),0,event)) %>%
group_by(yyyy,mm,dd,event) %>%
mutate(event = sum(event)) %>%
mutate(event = ifelse(event == 0, 1, event)) # If removed, the ungrouped values will have event = 0
輸出:
# A tibble: 17 x 5
# Groups: yyyy, mm, dd, event [4]
yyyy mm dd hour event
<int> <int> <int> <int> <dbl>
1 2011 5 1 10 1
2 2011 5 1 12 6
3 2011 5 1 13 6
4 2011 5 1 14 6
5 2011 5 1 15 6
6 2011 5 1 16 6
7 2011 5 1 17 6
8 2011 5 1 20 1
9 2011 5 2 11 8
10 2011 5 2 12 8
11 2011 5 2 13 8
12 2011 5 2 14 8
13 2011 5 2 15 8
14 2011 5 2 16 8
15 2011 5 2 17 8
16 2011 5 2 18 8
17 2011 5 3 10 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369330.html
下一篇:總結后如何考慮組內較大的日期
