I am sorry, I am not very clear indeed.
So my data structure is as following: a first column named iso with the name of countries, a second with the year, a third one with the gdp growth for each country every year and finally the gdp value at the first year of the period. So for example, I have the gdp value of England in 2016, its growth and I calculate the GDP value of 2017 using the loop. However when the country changes, the loop still uses the GDP value of the previous row (so using the GDP value of another country), which is my problem.
myData = data.frame(
iso=c("AE", "AE", "AF", "AF"),
year=c(2016, 2017, 2016, 2017),
GDP_growth=c(0.1, 0.2, 0.3, 0.4),
GDP_value=c(10, NA, 10, NA)
)
EDIT:
I tried the following idea but with no result.
myData = data.frame(
iso=c("AE", "AE", "AF", "AF"),
year=c(2016, 2017, 2016, 2017),
GDP_growth=c(0.1, 0.2, 0.3, 0.4),
GDP_value=c(10, NA, 10, NA)
)
my_function = function(x){
sapply(2:length(x), function(GDP_growth){
lag(x)*(1+GDP_growth)
})
}
myData <- myData %>%
group_by(iso) %>%
mutate(GDP_value=my_function(GDP_value))