当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-22
参见英文答案 Grouping functions (tapply, by, aggregate) and the *apply family9个 Calculate group mean (or other summary stats) and assign to original data4个 我试图在R中使用聚合函数,我希望输出数据框的维度保持不
参见英文答案 > 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
网友评论