Home > front end >  Calculation of Marginal Cost in Data Frame
Calculation of Marginal Cost in Data Frame

Time:01-14

Year Cost quantity shipped
2000 63.01359 2270
2001 61.64063 2558
2002 66.54081 3279
2003 64.02072 3656
2004 60.52792 3721

The above is a data frame that I am using for calculating marginal cost for each year, excepting the first year (2000). The formula for marginal cost is "change in cost/ change in quantity", which leads us to

61.64063 - 63.01359/ 2558-2270

for the marginal cost of 2001.

Year Cost quantity shipped Marginal cost
2000 63.01359 2270 0
2001 61.64063 2558 -0.00476
2002 66.54081 3279 xxx
2003 64.02072 3656 xxx
2004 60.52792 3721 xxx

The desired result is shown above. I know I can do this easily in excel with the indices and formulas, but I don't know how to do it in R. Any solutions are welcomed, thank you guys very much.

CodePudding user response:

You may use lag to get the previous value of a column.

library(dplyr)

dat <- dat %>%
        mutate(Marginal_Cost = (Cost-lag(Cost))/
                               (quantity_shipped - lag(quantity_shipped)))
dat

#  Year     Cost quantity_shipped Marginal_Cost
#1 2000 63.01359             2270            NA
#2 2001 61.64063             2558  -0.004767222
#3 2002 66.54081             3279   0.006796366
#4 2003 64.02072             3656  -0.006684589
#5 2004 60.52792             3721  -0.053735385

data

dat <- structure(list(Year = 2000:2004, Cost = c(63.01359, 61.64063, 
66.54081, 64.02072, 60.52792), quantity_shipped = c(2270L, 2558L, 
3279L, 3656L, 3721L)), row.names = c(NA, -5L), class = "data.frame")

CodePudding user response:

One possible way to solve your problem:

library(dplyr)

df %>% 
  mutate(Marginal_cost = c(NA, diff(Cost)/diff(quantity.shipped)))

  Year     Cost quantity.shipped Marginal_cost
1 2000 63.01359             2270            NA
2 2001 61.64063             2558  -0.004767222
3 2002 66.54081             3279   0.006796366
4 2003 64.02072             3656  -0.006684589
5 2004 60.52792             3721  -0.053735385
  • Related