【问题标题】:R: How to get my for loop to print a vectorR:如何让我的 for 循环打印矢量
【发布时间】:2017-04-25 19:39:58
【问题描述】:

我需要我的 for 循环来输出一个向量,而不仅仅是一系列答案。这是我的代码:

mean=211
sd=sqrt(558)
x=rnorm(100,mean,sd)
cost=40

for(i in c(1:100))
{
    if(x[i]<=200)
    {
        profit=x[i]-cost
    }
    else
    {
        profit=200-cost
    }
print(profit)
}

如何让它将不同的利润打印为一个向量?

【问题讨论】:

  • 我想你想要pmax(x, 200) - cost,fwiw。
  • @Frank 我觉得真的是pmin(x,200) - cost
  • 感谢您的帮助,我已经在 for 循环中将其更改为 pmin 而不是 if 和 else 但仍然无法获得向量输出?

标签: r for-loop if-statement


【解决方案1】:

例如,您可以从 profit_array &lt;- numeric(length(x)) 开始,然后在 FOR 循环中:

  • profit=x[i]-cost 之后添加一个带有profit_array[i] &lt;- profit 的新行
  • profit = 200-cost 之后添加一个带有profit_array[i] &lt;- profit 的新行
  • 最后,print(profit_array) 应该可以解决问题了

希望这会有所帮助!

编辑:实际上有些 cmets 效率更高。您可以使用矢量化代码绕过整个 FOR 循环:profit &lt;- pmin(x, 200) - cost

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2019-02-28
    • 2014-10-03
    相关资源
    最近更新 更多