【问题标题】:Syntax error with simple R function (Error: unexpected '}' in "}")简单 R 函数的语法错误(错误:“}”中的意外'}')
【发布时间】:2020-01-21 17:26:30
【问题描述】:
assert = function (expr, error) {
    # Original source: @max-gasner
    # https://stackoverflow.com/questions/8343509/better-error-message-for-stopifnot
    if (! expr) stop(error, call. = FALSE)
}


boolean = function(x, true_values=c("true", "t", "yes", "1"), false_values=c("false", "f", "no", "0"), assertion_message="Please choose either: TRUE or FALSE"){
    option = NULL
    x = tolower(as.character(x))
    (if x %in% true_values){
        option = TRUE
    }
    (if x %in% false_values){
        option = FALSE
    }
    assert(is.logical(options), assertion_message)
    return option
}

这是rstudio 中发生的情况:

> assert = function (expr, error) {
+     # Original source: @max-gasner
+     # https://stackoverflow.com/questions/8343509/better-error-message-for-stopifnot
+     if (! expr) stop(error, call. = FALSE)
+ }
> 
> 
> boolean = function(x, true_values=c("true", "t", "yes", "1"), false_values=c("false", "f", "no", "0"), assertion_message="Please choose either: TRUE or FALSE"){
+     option = NULL
+     x = tolower(as.character(x))
+     (if x %in% true_values){
Error: unexpected symbol in:
"    x = tolower(as.character(x))
    (if x"
>         option = TRUE
>     }
Error: unexpected '}' in "    }"
>     (if x %in% false_values){
Error: unexpected symbol in "    (if x"
>         option = FALSE
>     }
Error: unexpected '}' in "    }"
>     assert(is.logical(options), assertion_message)
Error in stop(error, call. = FALSE) : 
  object 'assertion_message' not found
>     return(option)
Error: no function to return from, jumping to top level
> }
Error: unexpected '}' in "}"

我检查了这个:Error: unexpected '}' in " }",它不是来自 unicode 字符。

【问题讨论】:

    标签: r syntax syntax-error


    【解决方案1】:

    问题在于(的位置

    (if x %in% true_values)
    ^^
    

    同样

    (if x %in% false_values)
    ^^
    

    应该是

    if(x %in% true_values)
    

    if(x %in% false_values)
    

    【讨论】:

    • 谢谢!来自 Python 时,我有时会对语法感到有些困惑。 R 中的错​​误消息有点误导。
    猜你喜欢
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多