来自另一个表的总和信息 [英] Sum information from another table

查看:60
本文介绍了来自另一个表的总和信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何汇总另一个表中的信息.示例:表Y具有销售值,该值在表X中通过"ID"列进行累加.

How do I sum information from another table. Example: The table Y has the sales value, which sums in the table X the values through the column "ID".

表X

Id <- c(1,25,30)
Product <- c("Shirt", "Pants", "Shorts")
X <- data.frame(Id, Product)

表Y

Id <- c(1,1,1,25,25,30,25,30)
sale_value <- c(250,250,250,300,300,150,300,150)
Y <- data.frame(Id,sale_value)

我需要在tabela X中添加一个名称为"Sale_total"的列,将表Y中的值(列"sale_values")相加,并通过列"Id"

I need add a column in tabela X with name "Sale_total", summing the values from table Y (column "sale_values"), throug column "Id"

推荐答案

您可以在基数R中使用aggregate Y,然后将mergeX一起使用:

You can use aggregate Y and then merge with X in base R:

merge(X, aggregate(sale_value ~ Id, Y, sum), by = 'Id')

结果:

  Id Product sale_value
1  1   Shirt        750
2 25   Pants        900
3 30  Shorts        300

tidyverse中与dplyr的左连接:

library(dplyr)
X %>% 
  left_join(Y %>% 
              group_by(Id) %>% 
              summarise(sale_total = sum(sale_value)),
            by = 'Id')

这篇关于来自另一个表的总和信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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