【问题标题】:Unexpected '{' and 'else'意外的“{”和“其他”
【发布时间】:2020-03-02 21:55:46
【问题描述】:

尝试创建一个可以保存“分数”向量的函数,然后该函数将确定分数的定性评级。我已经多次重新排列我的括号,但我仍然得到这些错误。 “else”也会出错。

    credit_fun <- function(scores){
      if (scores>300 & scores<579)(incbounds = TRUE){
    'Very Poor';
    } else if (scores>580 & scores<669)(incbounds = TRUE){
    'Fair';
    } else if (scores>670 & scores<739)(incbounds = TRUE){
    'Good';
    } else if (scores>740 & scores<799)(incbounds = TRUE){
    'Very Good';
    } else if (scores>800 & scores<850)(incbounds = TRUE){
    'Exceptional'}
}

【问题讨论】:

  • so if ((scores>300 & scores
  • 啊好吧,让我试试
  • 好的,意外的 'else' 消失了,但每行仍然出现“意外的 '{'
  • 对此不完全确定,我的同行也包括在内。我认为这是为了确保值保持在范围内?如果我在 if 语句中有约束,是否没有必要?
  • 我放弃了 incbounds,它确实摆脱了错误。它只返回向量中的第一个值。如何调整函数以使其与各种长度的向量兼容?

标签: r if-statement curly-braces


【解决方案1】:

我们可以使用betweencase_when

library(dplyr)
credit_fun <- function(scores) {
      case_when(between(scores, 300, 579) ~ "Very Poor",
                between(scores, 580, 669) ~ "Fair",
                between(scores, 670, 739) ~ "Good",
                between(scores, 740, 779) ~ "Very Good", 
                TRUE ~ "Exceptional")

  }

或者另一个选项是cut

credit_fun <- function(scores) {
           cut(scores, breaks = c(-Inf, 300, 580, 670, 740, Inf),
                 labels = c("Very Poor", "Fair", "Good", "Very Good", "Exceptional"))
  }

或者findInterval

credit_fun <- function(scores) {
   c("Very Poor", "Fair", "Good", "Very Good", "Exceptional")[findInterval(scores, 
                 c(300, 580, 670, 740))]
  }

【讨论】:

  • 我对 R 很陌生,我只下载了基本的 R 包。我收到“找不到函数case_when
  • @user12996093 你可以使用cutfindInterval,它来自base R。对于case_when,它来自dplyr。尝试install.packages('dplyr'),然后加载library(dplyr)
  • 剪切功能完美运行。由于 750 显示为异常,因此必须将中断调整到范围的顶端以限制每个范围的最大值。非常感谢您的帮助和耐心!
  • 我想这很有用,但您不认为指出原始代码中明显的错误会更有帮助吗? (很惊讶你没有使用findInterval :-)
  • 哦,等等,它在旁边。
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 2016-02-18
  • 1970-01-01
相关资源
最近更新 更多