0

Equation to be modeled in R

Structure of the Data

The variable gdp_pc_ppp corresponds to y in the equation. The variable gdp_pc_ppp is already sorted from the smallest to largest value. The variable world_pop_share corresponds to p in the equation.

I need to write code in R that creates a new variable as follows:

For the first row, it evaluates to NA 

   For the second row: (651.9531 - 378.5343)*9.568926e-03*2.636202e-03  

   For the third row: ((742.9709 - 651.9531)*8.084378e-03*9.568926e-03) 
             + ((742.9709 - 378.5343)*8.084378e-03*2.636202e-03) 

   For the fourth row: ((744.1971 - 742.9709)*1.878016e-03*8.084378e-03) 
              + ((744.1971 - 651.9531)*1.878016e-03*9.568926e-03)
              + ((744.1971 - 378.5343)*1.878016e-03*2.636202e-03) 

So on and so forth for the following observations.

I need to do this for different years, therefore, I was trying to do it within the tidy verse syntax.

For example:

d = d %>%
    group_by(year) %>%
    mutate( INSERT HERE FUNCTION THAT WOULD CALCULATE EQUATION ABOVE )

Thank you.

danday74
  • 52,471
  • 49
  • 232
  • 283
Talzzia
  • 13
  • 2

1 Answers1

0

I think these are your data, more or less.

data <- data.frame(country=c("Moz.", "Eth.", "Mya.", "Mal.", "Uga."),
                   year= c(1990, 1990, 1990, 1990, 1990),
                   gdp_pc_ppp=c(378.5, 651.9, 742.9, 744.2, 782.0),
                   world_pop_share=c(2.6e-3,9.5e-3,8.1e-3,1.8e-3,3.5e-3))

To do what you want, I wrote this function.

my.math <- function(data, y, p) {

  # check args
  if(!is.data.frame(data))
    stop("Bad input!")

  # Do the math
  out <- sapply(2:nrow(data), (function(i){
    p.i <- data[i, p]
    y.i <- data[i, y]
    sum(sapply(1:i, (function(j){
      p.tmp <- data[j, p]
      y.tmp <- data[j, y]
      (y.i - y.tmp) * p.i * p.tmp
    })), na.rm = TRUE)
  }))
  return(c(NA, out))
}

And this is how you can get your result. Does it work as expected?

my.math(data,
        y = 3, # your y is the third column
        p = 4) # your p is the fourth column)

In my hands, it returns:

[1]         NA 0.00675298 0.01467671 0.00330876 0.00934430
Damiano Fantini
  • 1,925
  • 9
  • 11