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

标签 r sum grouping

我在 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/

相关文章:

r - 在带有数据包 data.table 的 R 中,如何使 R 完整显示数据表?

c# - 小计关系数据表

python - 在另一个数组中的位置映射 numpy 数组和求和值

mysql - 选择 X 组中最大的 N 条记录

regex - 使用带有 sed 的正则表达式分组替换字符

r - 将数据框中的一列字符串转换为 R 中的数字(不是通常的类型)

r - 大型 data.frame 中的高效字符串值计数

r - 在 R 中处理具有相同 Id(键)列值的多行

mysql - 计算字段值出现次数最多的次数

r - 数据框中分组数据中每个观察值的标准误差