if else错误:R中的“}”中出现意外的'}'

时间:2015-10-31 16:43:09

标签: r if-statement

有史以来最简单的脚本,为什么我会收到错误:

<?php
// create array of ten objects with random values
$images = array();
for ($i = 0; $i < 10; $i++)
    $images[ $i ] = (object)array(
        'width' => rand(100, 1000)
    );

// print array
print_r($images);

// adapted function from Tim Copper's solution
// https://stackoverflow.com/a/5464961/496176
function closest($array, $member, $number) {
    $arr = array();
    foreach ($array as $key => $value)
        $arr[$key] = $value->$member;
    $closest = null;
    foreach ($arr as $item)
        if ($closest === null || abs($number - $closest) > abs($item - $number))
            $closest = $item;
    $key = array_search($closest, $arr);
    return $array[$key];
}

// object needed
$needed_object = closest($images, 'width', 320);

// print result
print_r($needed_object);
?>

如果我只是将其他地方放在}之后就没有问题了。

> x <- -5
> if(x > 0){
+     print("Non-negative number")
+ } 
> else{
Error: unexpected 'else' in "else"
>     print("Negative number")
[1] "Negative number"
> }
Error: unexpected '}' in "}"

我总是把它写成没有问题的第一条路;我疯了吗?

3 个答案:

答案 0 :(得分:5)

如果您以交互方式输入代码,R认为if子句在看到第一个关闭括号时就会完成。然后它“认为”else正在开始一个新的声明,这是不允许的。来自help("else")

  

特别是,你不应该在'}'之间换行        'else'以避免在输入'if ... else'时出现语法错误        在键盘或通过'源'构建。出于这个原因,一个        (有点极端)防守编程的态度总是如此        使用大括号,例如,用于'if'子句。

如果您使用R CMD BATCH,则此工作。您也可以使用括号,如帮助文件所示:

x <- -5
{ if(x > 0){
     print("Non-negative number")
  } 
  else {
     print("Negative number")
  }
}

或仅将else包含在与行括号相同的行中。

答案 1 :(得分:1)

这不是你的错。这就是R控制台的工作方式!当您键入右括号时,控制台希望不会有任何else ifelse子句,因此它会执行if子句。

解决方法是将整个if.. else子句括在括号中,如下所示:

x <- -5
{   
  if(x > 0){
     print("Non-negative number")
  } 
  else{
     print("Negative number")
  }
}

答案 2 :(得分:0)

从这个Documentation开始,你需要用这种方式输入它。

  

值得注意的是,else必须与if语句的结束括号位于同一行。

因此,即使您不处于交互模式,也可能会遇到问题。