I have a dataset like this
Company Year Value
A 22 15
A 23 17
A 24 13
A 25 20
B 22 187
B 23 153
B 24 135
C...ect
I need to make all values, for each company, equal to the value of 2022. Like this:
Company Year Value
A 22 15
A 23 15
A 24 15
A 25 15
B 22 187
B 23 187
B 24 187
C...ect
And then multiply each value by a given rate (eg. 2% for each value) that coumpounds. Like this:
Company Year Value
A 22 15
A 23 15x1,02
A 24 15x1,02^2
A 25 15x1,02^3
B 22 187
B 23 187x1,02
B 24 187x1,02^2
C...ect
Can someone help me please?
CodePudding user response:
df <- data.frame(
stringsAsFactors = FALSE,
Company = c("A", "A", "A", "A", "B", "B", "B"),
Year = c(22L, 23L, 24L, 25L, 22L, 23L, 24L),
Value = c(15L, 17L, 13L, 20L, 187L, 153L, 135L)
)
library(tidyverse)
df %>%
group_by(Company) %>%
mutate(Value = first(Value) * 1.02 ^ (row_number() - 1)) %>%
ungroup()
#> # A tibble: 7 x 3
#> Company Year Value
#> <chr> <int> <dbl>
#> 1 A 22 15
#> 2 A 23 15.3
#> 3 A 24 15.6
#> 4 A 25 15.9
#> 5 B 22 187
#> 6 B 23 191.
#> 7 B 24 195.
Created on 2022-03-18 by the reprex package (v2.0.1)
CodePudding user response:
You can do:
library(tidyverse)
df %>%
group_by(Company) %>%
mutate(Value = Value[Year == "22"]*(1.02^(0:(n()-1))))
Company Year Value
1 A 22 15.00000
2 A 23 15.30000
3 A 24 15.60600
4 A 25 15.91812
5 B 22 187.00000
6 B 23 190.74000
7 B 24 194.55480