我试图将一个数字除以两个 if 语句的结果之和。出于某种原因,R 在完成第一个 if 语句后忽略了两个 if 语句周围的括号,并且只对第一个 if 语句进行除法。在第一个 if 语句周围添加括号时,公式按预期工作。
问题是:这是为什么?
用 ifelse(y==2,4,1) 替换 if 语句可以解决它,以及额外的括号。我很好奇为什么第一次测试给了我意想不到的结果。
x <- 1
y <- 2
z <- 4
test1 <- z/(if(y==2){4}else{1}+if(x==1){4}else{1})
> print(test1)
[1] 1
test2 <- z/((if(y==2){4}else{1})+if(x==1){4}else{1})
> print(test2)
[1] 0.5
我希望 test1 和 test2 的结果都是 0.5
最佳答案
一个很好的问题。来自 R Language Definition :
Computation in R consists of sequentially evaluating statements. Statements, such as x<-1:10 or mean(y), can be separated by either a semi-colon or a new line.
此外,在
if
下:The if/else statement conditionally evaluates two statements. There is a condition which is evaluated and if the value is TRUE then the first statement is evaluated; otherwise the second statement will be evaluated. The if/else statement returns, as its value, the value of the statement that was selected. The formal syntax is
if ( statement1 ) statement2 else statement3
您遇到的问题是
{1}+if(x==1){4}else{1}
是一个有效的语句,因此 R 将其解释为 statement3。换句话说,来自 else
, 任何(块内)直到换行或分号只有在 if
时才会遇到声明是假的。通常,在类似
if (y == 2) {
4
} else {
1
}
我们知道,在最后一个大括号之后,if 语句已经完成,但表示表达式结束的是换行符,而不是右大括号。例如,这不会创建
a
if (y == 2) {
4
} else {
1
} -> a
关于r - 什么时候需要在 if 语句周围加上括号来控制 R 中公式的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527434/