[R] Question about expression parser for "return" statement
Dave DeBarr
ddebarr at uw.edu
Sun Nov 13 06:50:42 CET 2016
I've noticed that if I don't include parentheses around the intended return
value for the "return" statement, R will assume the first parenthetical
expression is the intended return value ... even if that parenthetical
expression is only part of a larger expression.
Is this intentional?
I'm guessing it is intentional; but since there is no warning about
ignoring the rest of the expression, it could lead to hard-to-find bugs.
Thanks,
Dave
Here's an example ...
dnorm(2, 0, 1)
normalDensityFunction = function(x, Mean, Variance) {
# no parentheses surrounding the entire "return" value
return (1/sqrt(2*pi*Variance))*exp(-(1/2)*((x - Mean)^2)/Variance)
}
normalDensityFunction(2, 0, 1) # incorrect answer
normalDensityFunction = function(x, Mean, Variance) {
# parentheses surrounding the entire "return" value
return ((1/sqrt(2*pi*Variance))*exp(-(1/2)*((x - Mean)^2)/Variance))
}
normalDensityFunction(2, 0, 1) # correct answer
[[alternative HTML version deleted]]
More information about the R-help
mailing list