Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregrate without reducing dimension of dataframe [duplicate]

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.

like image 702
Rohith Nagpal Avatar asked Mar 11 '23 23:03

Rohith Nagpal


1 Answers

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"
like image 51
akrun Avatar answered Apr 05 '23 23:04

akrun