Is there a more effective way of coding GDP growth in R rather than using [,] to identify the cells containing the relevant data?

Viewed 38

I've been working in the DataCamp Playgrounds, putting into practice the lessons I've completed in the R Data Science Career Track. I've been looking at the Gross Domestic Product Data, specifically Brazil.

I've calculated the GDP growth between 2006 (row 1, column 4 in the database I made named Brazil_2006_2016) and 2010 (row 5, column 4) in two ways.

The first was simply using the standard formula and copying and pasting the data into the space for code:

((2208871646202.82 - 1107640325472.35)/1107640325472.35)*100

This gives me an answer of 99.4213821405295, which looks right according the line chart I made using ggplot(). I did attempt to code this process using what I know of indexes in r:

Brazil_2006 <- Brazil_2006_2016 [1,4]
Brazil_2010 <- Brazil_2006_2016[5,4]

Following up with

((Brazil_2010 - Brazil_2006)/Brazil_2006)*100

This gave me the same answer, rounded to 4 places.

I want to improve my coding skills so this is the solution I prefer. However, I've seen other examples of calculating GDP growth using more complex coding which tbh I've found impossible to apply - lag() for example. My question is this:

Is there a better (more elegant?) way of coding this calculation?

@RuiBarradas I've added the output of dput(head((Belize_1960_1970) as that is the dataset I'm currently working on.

"Belize", "Belize", "Belize"), CountryCode = c("BLZ", "BLZ", 
"BLZ", "BLZ", "BLZ", "BLZ"), Year = c(1960, 1961, 1962, 1963, 
1964, 1965), Value = c(28071888.5622288, 29964370.7125857, 31856922.8615428, 
33749405.0118998, 36193826.1234775, 40069930.0699301)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))```
1 Answers

Here is a growth function in base R.
The data gdp is generated with a exponential growth rate equal to 0.05. The function below computes the growth rate of the entire vector with vectorized instructions.

growth <- function(x, default = 0) {
  n <- length(x)
  y <- (x[-1] - x[-n])/x[-n]
  c(default, y)
}

gdp <- (1 + 0.05)^(1:10)
growth(gdp)
#>  [1] 0.00 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

Created on 2022-09-04 by the reprex package (v2.0.1)

Related