gpt4 book ai didi

r - 创建组 ID 序列但省略特定行

转载 作者:行者123 更新时间:2023-12-05 09:28:36 25 4
gpt4 key购买 nike

我有这个数据框:

df <- structure(list(value = c("+", "+", "+", "-", "+", "-", "+", "+", 
"+", "+", "-", "+", "+", "+", "+", "+", "+", "+", "+", "+", "+",
"+", "+", "+", "+", "+", "+", "+", "+", "+", "+", "+", "+", "+",
"+", "+", "+", "+", "+")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -39L))

value
<chr>
1 +
2 +
3 +
4 -
5 +
6 -
7 +
8 +
9 +
10 +
# ... with 29 more rows

我想为每 4 行添加一个分组 ID,例如:

df %>% 
mutate(id = rep(row_number(), each=4, length.out = n()))

value id
1 + 1
2 + 1
3 + 1
4 - 1
5 + 2
6 - 2
7 + 2
8 + 2
9 + 3
10 + 3
... and so on

但我希望带有 - 的行被省略,例如:

df_expected
value id expected_id
1 + 1 1
2 + 1 1
3 + 1 1
4 - 1 1
5 + 2 1
6 - 2 2
7 + 2 2
8 + 2 2
9 + 3 2
10 + 3 2
11 - 3 3
12 + 3 3
13 + 4 3
14 + 4 3
15 + 4 3
16 + 4 4
17 + 5 4
18 + 5 4
19 + 5 4
20 + 5 5
21 + 6 5
22 + 6 5
23 + 6 5
24 + 6 6
25 + 7 6
26 + 7 6
27 + 7 6
28 + 7 7
29 + 8 7
30 + 8 7
31 + 8 7
32 + 8 8
33 + 9 8
34 + 9 8
35 + 9 8
36 + 9 9
37 + 10 9
38 + 10 9
39 + 10 9

最佳答案

一个选项是对“值”不是-的行进行子集化,使用与OP帖子中相同的代码创建列“id”,然后填充 NA

library(data.table)
library(dplyr)
library(tidyr)
setDT(df)[value != "-", id := rep(seq_len(.N), each = 4, length.out = .N) ]
df %>%
fill(id, .direction = "updown")

-输出

    value    id
<char> <int>
1: + 1
2: + 1
3: + 1
4: - 1
5: + 1
6: - 2
7: + 2
8: + 2
9: + 2
10: + 2
11: - 3
12: + 3
13: + 3
14: + 3
15: + 3
16: + 4
17: + 4
18: + 4
19: + 4
20: + 5
21: + 5
22: + 5
23: + 5
24: + 6
25: + 6
26: + 6
27: + 6
28: + 7
29: + 7
30: + 7
31: + 7
32: + 8
33: + 8
34: + 8
35: + 8
36: + 9
37: + 9
38: + 9
39: + 9

或者使用 dplyr 和来自 tidyrfill - 而不是在整个序列上创建 rep,子集row_number() 其中 'value' 不等于 '-',并使用 replace 仅分配给那些具有 rep 输出的元素

df %>% 
mutate(id = replace(rep(NA_integer_, n()), value != "-",
rep(row_number()[value != "-"], each = 4,
length.out = sum(value != "-")))) %>%
fill(id, .direction = "updown")

关于r - 创建组 ID 序列但省略特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71279508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com