在 R 中为需求计划创建弹性函数时出错

问题描述

尝试创建一个函数,该函数接收需求计划并在数据框中添加一列,该列在每个点都具有弹性。如果您在下面运行我的代码,您会得到一个数据框,每列中都有重复的值。我的 for 循环有问题吗?

elasticity <- function(df){
  df$PCP <- NULL #percentage change in price 
  df$PCQ <- NULL #percentage change in quantity
  df$elasticity<- NULL #elasticity
  for (i in 1:length(df$Price)){
    df$PCP[i] <- 100*(df$Price[i]-df$Price[i+1])/(0.5*(df$Price[i]+df$Price[i+1])) 
  df$PCQ[i] <- 100*(df$Quantity[i+1]-df$Quantity[i])/(0.5*(df$Quantity[i]+df$Quantity[i+1]))
  df$elasticity[i] <- df$PCQ[i]/df$PCP[i]
  return(df)
  }
}
df <- data.frame("Price"=c(7:0),"Quantity"=seq(0,14,by=2))
elasticity(df)

解决方法

您需要将 return 语句放在循环之外。

我认为将 return 放在循环中会完全退出函数,这就是生成第一个结果的原因。来自 datamentor.io,“如果它不是函数的最后一条语句,它将过早结束将控件带到调用它的位置的函数。”

sample_function <- function(){
  print("Hi!")
  for(i in seq_along(rep(1,6))){
    return(i)
    print("This is not evaluated")
  }
  print("This is not evaluated either")
}
sample_function()

> sample_function()
[1] "Hi!"
[1] 1

另外,既然你在做i +/- i + 1,请注意“一对一”。

elasticity <- function(df){
  df$PCP <- NULL #percentage change in price 
  df$PCQ <- NULL #percentage change in quantity
  df$elasticity<- NULL #elasticity
  for (i in seq_along(df$Price)){
    df$PCP[i] <- 100*(df$Price[i]-df$Price[i+1])/(0.5*(df$Price[i]+df$Price[i+1])) 
    df$PCQ[i] <- 100*(df$Quantity[i+1]-df$Quantity[i])/(0.5*(df$Quantity[i]+df$Quantity[i+1]))
    df$elasticity[i] <- df$PCQ[i]/df$PCP[i]
    df
  }
  return(df)
}

> elasticity(df)
  Price Quantity       PCP       PCQ  elasticity
1     7        0  15.38462 200.00000 13.00000000
2     6        2  18.18182  66.66667  3.66666667
3     5        4  22.22222  40.00000  1.80000000
4     4        6  28.57143  28.57143  1.00000000
5     3        8  40.00000  22.22222  0.55555556
6     2       10  66.66667  18.18182  0.27272727
7     1       12 200.00000  15.38462  0.07692308
8     0       14        NA        NA          NA