Reputation: 25
I have this data frame with 3 columns and I need a 4th column which makes the increase of the value for each Fund for each date, in this case it is only possible for 2022-01-02 values.
Date <- c("2022-01-01","2022-01-01","2022-01-01","2022-01-02","2022-01-02","2022-01-02")
Fund <-c("A","B","C","C","A","B")
Values <- c(10,10,10,13,17,15)
For example this would be one result
Date | Fund | Value | Increase % |
---|---|---|---|
2022-01-02 | A | 17 | 70% |
Upvotes: 1
Views: 37
Reputation: 887251
An approach is to take the diff
after grouping by 'Fund' and divide by the first
value
library(dplyr)
df1 %>%
group_by(Fund) %>%
mutate(Prop = 100 * c(0, diff(Values)/first(Values))) %>%
ungroup
Or could be divide by the lag
of 'Values'
df1 %>%
group_by(Fund) %>%
mutate(Prop = 100 * c(0, diff(Values))/lag(Values)) %>%
ungroup
Upvotes: 1