gpt4 book ai didi

r - 沿着某些值的运行,填充第二列中的第一个值

转载 作者:行者123 更新时间:2023-12-03 23:33:22 25 4
gpt4 key购买 nike

我有样本数据:

testSample <- data.table(a = rnorm(n = 20, mean = 2, sd = 1),
b = sample(c(0,1), replace=TRUE, size=20))

testSample
a b
1: 3.1731458 0
2: 1.0687438 1
3: 2.9078655 1
4: 1.5675078 0
5: 2.7825992 0
6: 1.3672285 1
7: 3.6178619 0
8: 2.9067640 1
9: 2.5021129 0
10: 2.7672849 1
11: 2.3501007 1
12: -0.2923344 0
13: 0.3920071 1
14: 2.5113855 0
15: 2.2192234 1
16: 0.5913632 0
17: 0.8864734 1
18: 1.9187394 0
19: 1.1238824 1
20: 1.5001240 1

在“b”列中有交替运行的 01。在 1 的每次连续运行中,我希望在每个新列的第一个 1 的索引处填充一个新列“c”中的“a”列中的数字运行。

当'b'为0时,'c'应为NA

我手动填写新的“c”列的所需输出:

             a b         c
1: 3.1731458 0 NA
2: 1.0687438 1 1.0687438 # <- run of 1.
3: 2.9078655 1 1.0687438 # <- All rows filled with the first 'a' value in the run
4: 1.5675078 0 NA
5: 2.7825992 0 NA
6: 1.3672285 1 1.3672285 # <-
7: 3.6178619 0 NA
8: 2.9067640 1 2.9067640 # <-
9: 2.5021129 0 NA
10: 2.7672849 1 2.7672849 # <- run of 1
11: 2.3501007 1 2.7672849 # <- All rows filled with the first 'a' value in the run
12: -0.2923344 0 NA
13: 0.3920071 1 0.3920071
14: 2.5113855 0 NA
15: 2.2192234 1 2.2192234
16: 0.5913632 0 NA
17: 0.8864734 1 0.8864734
18: 1.9187394 0 NA
19: 1.1238824 1 1.1238824
20: 1.5001240 1 1.1238824

最佳答案

set.seed(47)
testSample <- data.table(a = rnorm(n = 20, mean = 2, sd = 1),
b = sample(c(0,1), replace=TRUE, size=20))

testSample[, grouper := rleid(b)][b == 1, c := a[1], by = .(grouper)]
testSample
# a b grouper c
# 1: 3.9946963 0 1 NA
# 2: 2.7111425 0 1 NA
# 3: 2.1854053 1 2 2.1854053
# 4: 1.7182350 0 3 NA
# 5: 2.1087755 0 3 NA
# 6: 0.9142625 1 4 0.9142625
# 7: 1.0145178 1 4 0.9142625
# 8: 2.0151309 1 4 0.9142625
# 9: 1.7479541 1 4 0.9142625
# 10: 0.5342497 1 4 0.9142625
# 11: 1.0775438 0 5 NA
# 12: 2.0396024 0 5 NA
# 13: 2.4938202 0 5 NA
# 14: 0.1717708 1 6 0.1717708
# 15: 2.0914729 0 7 NA
# 16: 2.6707792 1 8 2.6707792
# 17: 1.9189219 0 9 NA
# 18: 3.2642411 0 9 NA
# 19: 1.2966118 1 10 1.2966118
# 20: 1.9594218 0 11 NA

当然,您可以在完成后删除 grouper 列。

关于r - 沿着某些值的运行,填充第二列中的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66340627/

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