根据 R 中列中的截止值将数据框拆分为每个因素的段

Splitting data frame into segments for each factor based on a cutoff value in a column in R

我目前正在使用一个数据框,其中包含具有相应时间戳的观察结果。请参阅下面的数据集子样本。

现在,我想根据秒的时差将df分成更小的段 柱子。但是,我不想创建多个新的 df,但我想为不同的段分配不同的“id”,并对第一列中的每个因素执行此操作。

即假设我的截止时间为 0.4 天。现在,我想遍历数据框,一旦时差大于 0.4 天,我希望将 A.1 中的 ID 更改为 A.2。只要时差小于 0.4 天,id 就会保持 A.2。但是,只要下一行的时差大于 0.4 天,id 就应该更改为 A.3 等(请查看所需的输出)。

数据集的子样本:

1  A.1 2019-02-04 22:33:41  0.0000000
2  A.1 2019-02-05 13:28:38  0.6214931
3  A.1 2019-02-05 13:28:38  0.0000000
4  A.1 2019-02-05 22:25:00  0.3724769
5  A.1 2019-02-06 16:13:35  0.7420718
6  A.1 2019-02-07 22:55:14  1.2789236
7  B.1 2019-02-07 22:55:14  0.0000000
8  B.1 2019-02-07 22:55:14  0.0000000
9  B.1 2019-02-08 12:42:42  0.5746296
10 B.1 2019-02-08 22:26:09  0.4051736
11 C.1 2019-02-08 22:26:09  0.0000000
12 C.1 2019-02-08 22:26:09  0.0000000
13 C.1 2019-02-08 22:26:09  0.0000000
14 C.1 2019-02-08 22:26:09  0.0000000
15 C.1 2019-02-12 11:23:57  3.5401389

期望的输出:

1  A.1 2019-02-04 22:33:41  0.0000000
2  A.2 2019-02-05 13:28:38  0.6214931
3  A.2 2019-02-05 13:28:38  0.0000000
4  A.2 2019-02-05 22:25:00  0.3724769
5  A.3 2019-02-06 16:13:35  0.7420718
6  A.4 2019-02-07 22:55:14  1.2789236
7  B.1 2019-02-07 22:55:14  0.0000000
8  B.1 2019-02-07 22:55:14  0.0000000
9  B.2 2019-02-08 12:42:42  0.5746296
10 B.3 2019-02-08 22:26:09  0.4051736
11 C.1 2019-02-08 22:26:09  0.0000000
12 C.1 2019-02-08 22:26:09  0.0000000
13 C.1 2019-02-08 22:26:09  0.0000000
14 C.1 2019-02-08 22:26:09  0.0000000
15 C.2 2019-02-12 11:23:57  3.5401389

data.table中:

dt[, V1 := paste0("A.", 1+cumsum(V4 >= 0.4))]

dplyr中:

df %>%
  mutate(V1 = paste0("A.", 1+cumsum(V4 >= 0.4)))

检查diff误差是否大于一天秒数的 .4 倍并计算 cumsum

paste0('A.', cumsum(c(0, diff(dat$X3)) > (24*60*60)*.4) + 1)
# [1] "A.1" "A.2" "A.2" "A.2" "A.3" "A.4" "A.4" "A.4" "A.5" "A.6" "A.6" "A.6"
# [13] "A.6" "A.6" "A.7"

注意:如果你有时间做字符格式,先做

dat$X3 <- as.POSIXct(dat$X3)

获取"POSIXt"格式,以秒为单位存储。


数据:

dat <- structure(list(X1 = 1:15, X2 = c("A.1", "A.1", "A.1", "A.1", 
"A.1", "A.1", "A.1", "A.1", "A.1", "A.1", "A.1", "A.1", "A.1", 
"A.1", "A.1"), X3 = structure(c(1549316021, 1549369718, 1549369718, 
1549401900, 1549466015, 1549576514, 1549576514, 1549576514, 1549626162, 
1549661169, 1549661169, 1549661169, 1549661169, 1549661169, 1549967037
), class = c("POSIXct", "POSIXt"), tzone = ""), X4 = c(0, 0.6214931, 
0, 0.3724769, 0.7420718, 1.2789236, 0, 0, 0.5746296, 0.4051736, 
0, 0, 0, 0, 3.5401389)), row.names = c(NA, -15L), class = "data.frame")