你在R中可能遇到的一个常见错误是:
Error: unexpected 'else' in "else"
这个错误通常发生在你把else语句放在R语言中新行的开头时。
本教程解释了如何在实践中修复这个错误。
如何重现该错误
假设我们试图使用if else语句根据一个变量的值来打印一个特定的字符串:
#define x
x <- 5
#use if else statement to print string
if(x < 7) {
print("x is less than 7")
}
else {
print("x is not less than 7")
}
Error: unexpected 'else' in "else"
我们收到一个错误,因为我们把else语句放在了一个全新的行的开头。
如何修复该错误
要解决这个错误,我们只需要将else语句往上移一行,使其出现在第一个闭合的大括号之后即可:
#define x
x <- 5
#use if else statement to print string
if(x < 7) {
print("x is less than 7")
} else {
print("x is not less than 7")
}
[1] "x is less than 7"
这一次我们没有收到错误,而且if else语句打印出字符串 "x小于7",因为x确实小于7。
其他资源
下面的教程解释了如何修复R中的其他常见错误:
如何修复:(list)对象不能被胁迫为'double'类型
如何在R中修复:ExtractVars中的无效模型公式
如何在R中修复:替换长度为0