首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R中需求计划弹性函数创建中的错误

R中需求计划弹性函数创建中的错误
EN

Stack Overflow用户
提问于 2021-01-04 19:59:27
回答 1查看 61关注 0票数 0

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

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-05 04:21:18

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

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

代码语言:javascript
复制
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,那么要注意“一对一”。

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65569046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档