上面是我用来计算每年边际成本的数据框,第一年(2000 年)除外。边际成本的公式是“成本变化/数量变化”,这使我们可以得出
61.64063 - 63.01359/2558-2270
2001 年的边际成本。
期望的结果如上所示。我知道我可以在 excel 中使用索引和公式轻松做到这一点,但我不知道如何在 R 中做到这一点。欢迎任何解决方案,非常感谢你们。
最佳答案
您可以使用lag
来获取列的先前值。
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
数据
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")
关于r - 数据框中边际成本的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75116728/