1

I need to calculate the area between two curves. One curve - country’s GDP per capita, other curve - GDP trend. I tried to use the integrate function in my code below but the calculated area is not accurate.

My code includes unnecessary area before and after the intersection points. I need to calculate the area where the GDP curve is below the GDP trend curve (1).

GDP_GR <- ts(GR, start = c(2000, 1), frequency = 4)
gdp_gr <- log(GDP_GR)
y.pot_gr <- hpfilter(gdp_gr, freq = 1600)$trend
ts.plot(gdp_gr)
y.pot_gr
lines(y.pot_gr, col = "blue")
# area: 
y.c_gr <- window(gdp_gr, start = c(2020, 1), end = c(2021, 1))
y.pot.c_gr <- window(y.pot_gr, start = c(2020, 1), end = c(2021, 1))
n <- length(y.c_gr)
x <- seq(1, n, 1)
plot(x, y.c_gr, type = "l", lwd = 1.5,
     ylim = c(min(c(y.c_gr, y.pot.c_gr)), max(c(y.c_gr, y.pot.c_gr))),
     xlab = "Time", ylab = "GDP", xaxt = "n")
lines(x, y.pot.c_gr, lty = 2, lwd = 1.5)
axis(1, at = 1:n, labels = ENTRY[81:85])
polygon(c(x, rev(x)),c(y.c_gr, rev(y.pot.c_gr)),
        col = "lightgrey", border = NA)
function_1 <- approxfun(x, y.c_gr - y.pot.c_gr)
function_2 <- function(x) {  abs(function_1(x)) }
integrate(function_2, 1, n)

How can I improve my code?

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
nerus
  • 11
  • 2
  • To get the most help, it's a good idea to include a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Kat Dec 22 '21 at 04:08
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Dec 30 '21 at 17:12

0 Answers0