Home > Blockchain >  Calculating the change in % of data by year
Calculating the change in % of data by year

Time:11-15

I am trying to calculate the % change by year in the following dataset, does anyone know if this is possible?

I have the difference but am unsure how we can change this into a percentage

C diff(economy_df_by_year$gdp_per_capita)

df
 year            gdp
 1998           8142.
 1999           8248.
 2000           8211.
 2001           7926.
 2002           8366.
 2003          10122.
 2004          11493.
 2005          12443.
 2006          13275.
 2007          15284.

CodePudding user response:

Assuming that gdp is the total value, you could do something like this:

library(tidyverse)
tribble(
  ~year,            ~gdp,
  1998,          8142,
  1999,          8248,
  2000,          8211,
  2001,          7926,
  2002,          8366,
  2003,         10122,
  2004,         11493,
  2005,         12443,
  2006,         13275,
  2007,         15284
) -> df
df |> 
  mutate(pdiff = 100*(gdp - lag(gdp))/gdp)
#> # A tibble: 10 × 3
#>     year   gdp  pdiff
#>    <dbl> <dbl>  <dbl>
#>  1  1998  8142 NA    
#>  2  1999  8248  1.29 
#>  3  2000  8211 -0.451
#>  4  2001  7926 -3.60 
#>  5  2002  8366  5.26 
#>  6  2003 10122 17.3  
#>  7  2004 11493 11.9  
#>  8  2005 12443  7.63 
#>  9  2006 13275  6.27 
#> 10  2007 15284 13.1

Which relies on the tidyverse framework.

If gdp is the difference, you will need the total to get a percentage, if that is what you mean by change in percentage by year.

CodePudding user response:

df$change <- NA
df$change[2:10] <- (df[2:10, "gdp"] - df[1:9, "gdp"]) / df[1:9, "gdp"]

This assigns the yearly GDP growth to each row except the first one where it remains as NA

CodePudding user response:

df$diff <- c(0,diff(df$gdp))
df$percentDiff <- 100*(c(0,(diff(df$gdp)))/(df$gdp - df$diff))

This is another possibility.

  •  Tags:  
  • r
  • Related