汇总所选行 [英] Summarising among the selected rows

查看:42
本文介绍了汇总所选行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据文件,例如:

Hi I have a data file like this sample:

a<-tribble(
  ~s.no,~a,~b,~volume,
  1,51,52,200,
  2,52,51,500,
  3,51,58,44,
  4,58,51,22
)
  

此表是什么?

行告诉两个方向上每条道路的流量.例如:s.no 1显示道路51至52上的交通量,类似s.no,2显示道路连接处但沿反方向的交通量:52至51.

The rows tell the volume in each road in both the directions. Eg: s.no 1 shows volume on road 51 to 52, similarly s.no, 2, shows volume on the smae link but in reverse direction: 52 to 51.

我想要什么?

我希望将两个方向上的音量总和为一个,例如:道路51至52的音量应为200 + 500.在R中有可能吗?以下是我期望作为输出的示例说明.

I want volume on both directions to be summed up into one, eg: road 51 to 52 should have 200+500 as volume. is it possible in R ? The following is the sample illustration of what i expect as a output.

推荐答案

您可以尝试

library(tidyverse)
a %>% 
  group_by(gr= a + b) %>% 
  summarise(s.no = min(s.no),
            a = first(a),
            b = first(b),
            vol = sum(volume)) 
# A tibble: 2 x 5
     gr  s.no     a     b   vol
  <dbl> <dbl> <dbl> <dbl> <dbl>
1   103     1    51    52   700
2   109     3    51    58    66

一种更通用的方法,其中考虑了 a + b 的相似总和,例如 51 + 52 50 + 53

A more generalized way taking into account similar sums of a+b e.g. 51 + 52 vs. 50 + 53

a %>% 
  pivot_longer(c(a, b)) %>% 
  group_by(s.no) %>% 
  mutate(gr = toString(sort(value))) %>% 
  pivot_wider() %>% 
  group_by(gr) %>% 
  summarise(s.no = min(s.no),
            volume = sum(volume)) %>% 
  separate(gr, into = letters[1:2])
# A tibble: 2 x 4
  a     b      s.no volume
  <chr> <chr> <dbl>  <dbl>
1 51    52        1    700
2 51    58        3     66

这篇关于汇总所选行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆