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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With