加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

聚合而不减少数据帧的维度

发布时间:2020-12-14 04:48:33 所属栏目:百科 来源:网络整理
导读:参见英文答案 Grouping functions (tapply,by,aggregate) and the *apply family????????????????????????????????????9个 ???????????? Calculate group mean (or other summary stats) and assign to original data????????????????????????????????????4
参见英文答案 > Grouping functions (tapply,by,aggregate) and the *apply family????????????????????????????????????9个
>???????????? Calculate group mean (or other summary stats) and assign to original data????????????????????????????????????4个
我试图在R中使用聚合函数,我希望输出数据框的维度保持不变.例如:假设我有以下数据框

Name------Type------    Price   
Prod1-----A--------       $1
Prod2----A---------       $5
Prod3----B----------       $7
Prod4-----B---------       $9

在R中使用聚合函数后,通过聚合Type和函数作为价格的总和.我得到以下结果:

Type-------Value
A-----------6
B-----------16

但是,我希望数据框的维度保持不变.例如:

Name-----Type----Price----Value  
Prod1----A-------$1-------$6
Prod2----A-------$5--------$6
Prod3----B--------$7-------$16
Prod 4----B-------$9--------$16

我不想在这个应用程序中使用Loop.请建议任何其他方式这样做.

解决方法

使用dplyr,

library(dplyr)
df %>% 
  group_by(Type) %>% 
  mutate(Value = sum(Price))

或使用data.table,

library(data.table)
setDT(df)[,Value := sum(Price),by = Type]

#    Name Type Price Value
#1:   P1    A     1     6
#2:   P1    A     5     6
#3:   P3    B     7    16
#4:   P4    B     9    16

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读