4

I am trying to use the aggregate function in R where I want the dimension of the output data frame to remain unchanged. For example: Let's say I have the following data frame

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

After using aggregate function in R by aggregating on Type and function as Sum of price. I get the following result:

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

However, I want the dimension of the data frame to remain same. For Example:

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

I do not want to use Loop for this application. Please suggest any other way of doing this.

zx8754
  • 52,746
  • 12
  • 114
  • 209

2 Answers2

5

We can use ave from base R

df1$Value <- with(df1, paste0("$", ave(as.numeric(sub("[$]", "", Price)), 
                          Type, FUN = sum)))
df1$Value
#[1] "$6"  "$6"  "$16" "$16"
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Using dplyr,

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

or using 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
Sotos
  • 51,121
  • 6
  • 32
  • 66