楼主: garethlee
4442 2

[问答] 关于For Loop 里中断循环 [推广有奖]

  • 0关注
  • 0粉丝

博士生

18%

还不是VIP/贵宾

-

威望
0
论坛币
1595 个
通用积分
13.4516
学术水平
0 点
热心指数
2 点
信用等级
0 点
经验
1250 点
帖子
14
精华
0
在线时间
492 小时
注册时间
2010-1-19
最后登录
2024-3-13

10论坛币
刚接触R语言菜鸟,问题小白不要见怪。

题目:

A car takes 40 hours of labor and 1 ton of steel

A truck takes 60 hours and 3 hours of steel

Resources: 1600 hours of labor and 70 tons of steel eachweek.



建立一个R代码,使过高计划产量(例如30辆轿车与20辆卡车),或者过低的计划产量逐步调整到最优化水平(最大量生产+资源剩余也不多).


起始代码:

factory <- matrix(c(40,1,60,3),nrow=2,
   dimnames=list(c("labor","steel"),c("cars","trucks")))
available <- c(1600,70); names(available) <- rownames(factory)
slack <- c(8,1); names(slack) <- rownames(factory)
output <-c(30,20); names(output) <- colnames(factory)

passes <- 0 # How many times have we  been around the loop?
repeat {   
     passes <- passes + 1   
     needed <- factory %*% output # What do we need for that output level?   # If we're not using too much, and are within the slack, we're done   
if (all(needed <= available) &&       all((available - needed) <= slack)) {     
break()   
}   
# If we're using too much of everything, cut back by 10%   if (all(needed > available)) { output <- output * 0.9     next()   
}   

# If we're using too little of everything, increase by 10%   if (all(needed < available)) {  output <- output * 1.1     next()   
}   

# If we're using too much of some resources but not others, randomly   # tweak the plan by up to 10%   
output <- output * (1+runif(length(output),min=-0.1,max=0.1))
}



要求:以for loop 代替上面代码里的repeat loop.


问题来了:在建立 for loop() 时候,()里面循环的次数passes不是预先知道的,所以无法设定。那如何让R在函数达到最优化的时候,自动放弃执行for loop 命令里面剩余的循环次数。(例如假设最大的循环次数设定为2000,达到最优化的时候,循环次数是1200,如何让R放弃执行剩余的800次?)





最佳答案

lww1993 查看完整内容

你直接用for(i in 1:1e3)代替repeat就可以了。
关键词:loop For Resources resource sources available factory trucks matrix names
沙发
lww1993 发表于 2014-9-15 15:46:59 |只看作者 |坛友微信交流群
你直接用for(i in 1:1e3)代替repeat就可以了。
已有 2 人评分经验 论坛币 学术水平 热心指数 收起 理由
dxystata + 20 + 20 + 1 + 1 热心帮助其他会员
admin_kefu + 50 热心帮助其他会员

总评分: 经验 + 20  论坛币 + 70  学术水平 + 1  热心指数 + 1   查看全部评分

使用道具

藤椅
lww1993 发表于 2014-9-15 16:31:51 |只看作者 |坛友微信交流群
这里的break函数会直接跳出循环。

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-5-10 19:39