gpt4 book ai didi

r - 如何按顺序按组对值求和

转载 作者:行者123 更新时间:2023-12-04 01:12:49 24 4
gpt4 key购买 nike

我在 duration 列中有一个包含持续时间值的数据框并将列中的值分组 gaze_focus .

df1
duration gaze_focus
29 1.011 periphery
31 1.590 center
33 1.582 center
35 0.571 periphery
37 0.561 center
39 2.136 center
41 0.181 periphery
43 1.475 center
45 0.177 periphery
47 0.940 periphery
49 2.102 center
我想计算 的总和紧邻相同组值 得到这个结果:
df2
duration gaze_focus
1 1.011 periphery
2 3.172 center
3 0.571 periphery
4 2.697 center
5 0.181 periphery
6 1.475 center
7 1.117 periphery
8 2.102 center
我知道可以使用例如按组求和等数学运算 aggregatetapply但我不知道如何按小块按组对值求和。帮助表示赞赏!
可重现的数据:
df1 <- structure(list(duration = c(1.011, 1.59, 1.582, 0.571, 0.561, 
2.136, 0.181, 1.475, 0.177, 0.94, 2.102), gaze_focus = c("periphery",
"center", "center", "periphery", "center", "center", "periphery",
"center", "periphery", "periphery", "center")), row.names = c(29L,
31L, 33L, 35L, 37L, 39L, 41L, 43L, 45L, 47L, 49L), class = "data.frame")

最佳答案

dplyr选项可以是:

df1 %>%
group_by(gaze_focus, rleid = with(rle(gaze_focus), rep(seq_along(lengths), lengths))) %>%
summarise_all(sum) %>%
arrange(rleid)

gaze_focus rleid duration
<chr> <int> <dbl>
1 periphery 1 1.01
2 center 2 3.17
3 periphery 3 0.571
4 center 4 2.70
5 periphery 5 0.181
6 center 6 1.48
7 periphery 7 1.12
8 center 8 2.10

关于r - 如何按顺序按组对值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64291402/

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