Reputation: 323
I have a df that looks like that:
df1 <- data.frame(country = c("C1","C1","C2","C2"),year = c(1998,2001,1998,2001), amount = c(11000,11500,5000,4100))
I created another df based on the first one as follow:
df2 <- aggregate(amount ~ year, df1, sum)
I would to create a new column df1$ratio
corresponding to the amount ration of each ID for each year. it should look like:
df3 <- data.frame(country = c("C1","C1","C2","C2"),year = c(1998,2001,1998,2001), amount = c(11000,11500,5000,4100), ratio = c(.6875, .7372,.3125,.2628))
Any Idea?
Upvotes: 1
Views: 34
Reputation: 887221
Instead of two step process, it can be done with ave
from base R
df1$ratio <- with(df1, amount/ave(amount, year, FUN = sum))
Or with mutate
from dplyr
library(dplyr)
df1 %>%
group_by(year) %>%
mutate(ratio = amount/sum(amount))
Upvotes: 1