【问题标题】:R debugging nested ifelse() statementR 调试嵌套 ifelse() 语句
【发布时间】:2017-10-21 23:19:03
【问题描述】:

当我逐行运行此代码时,它可以工作,但如果我运行整个代码块,它会给我一个错误。 我在这里要做的是
ifelse(,{yes; ifelse(,{yes,no})}, no)

ifelse(myfunct(R) >= myfunct(worst_point), 
 {IC <- C - 0.5 * (R - C); ifelse(myfunct(IC) < myfunct(worst_point), {points[[which.max(result)]] <- IC},
  for (i in 2:(n+1)) {points[[i]] <- best_point + 0.5 * (points[[i]] - best_point)})},
  for (i in 2:(n+1)) {points[[i]] <- best_point + 0.5 * (points[[i]] - best_point)})

但它给了我一个错误:

Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test &  : 
  replacement has length zero
In addition: Warning message:
In rep(no, length.out = length(ans)) :
  'x' is NULL so the result will be NULL

它给我一个错误的部分是 ifelse() 语句中的 for 循环,我不知道为什么,有人可以帮助我理解这个错误消息吗?

【问题讨论】:

  • 看起来你想使用真正的if-else 块。有关该概念的合理介绍,请参阅此页面:programiz.com/r-programming/if-else-statement
  • @NickNimchuk 嘿,一些使用真正的 if-else 块是如何工作的,.. 我使用 ifelse() 因为以前真正的 if-else 块没有链接多个嵌套的 if 语句,但也许我犯了一个错误.. 谢谢。

标签: r optimization


【解决方案1】:

我认为问题出在ifelse()yesno 参数中。该函数旨在返回与其test 参数形状相同的值。在这里,我尝试使用 if()else 语句重写它,并且根据您的评论,您已经成功地做到了。

if(myfunct(R) >= myfunct(worst_point)) {
  IC <- C - 0.5 * (R - C)
  if(myfunct(IC) < myfunct(worst_point)) {
    points[[which.max(result)]] <- IC
    }else{for (i in 2:(n+1)) {
                points[[i]] <- best_point + 0.5 * (points[[i]] - best_point)
                } 
    }
  }else{for (i in 2:(n+1)) {
    points[[i]] <- best_point + 0.5 * (points[[i]] - best_point)}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2014-07-12
    相关资源
    最近更新 更多