The answer is very simple: parentheses. (Also think about "operator
precedence".) If you assign rn <- 3, then 1:rn-1 is:
[1] 0 1 2
The "-" operator is applied *after* the ":" operator.
You want 1:(rn-1) which gives
[1] 1 2
and the desired result.
cheers,
Rolf Turner
On 18/04/20 7:55 am, Monica Palaseanu-Lovejoy wrote:
Hi,
I wrote a relatively simple function. If i run the code inside the function
line by line i am getting the result i was expecting, but if i run the
function, i get a different result.
The function:
grr1 <- function(rn) {
r.up <- c()
for (i in 1:rn-1) {
if (i%%2==0) ru <- seq(1,i) else ru <- seq(i,1)
r.up <- c(r.up, ru)
}
return(r.up)
}
So, if rn is 3 for example i would expect to get 1 1 2
grr1(3)
[1] 1 0 1 1 2
If i run it line by line inside the function:
r.up <- c()
r.up
NULL
i=1
if (i%%2==0) ru <- seq(1,i) else ru <- seq(i,1)
ru
[1] 1
r.up <- c(r.up, ru)
r.up
[1] 1
i=2
if (i%%2==0) ru <- seq(1,i) else ru <- seq(i,1)
ru
[1] 1 2
r.up <- c(r.up, ru)
r.up
[1] 1 1 2
So - i am getting the result i am expecting. From where the 1 0 before what
i expect as a result comes from? I am sure i am doing some very basic
error, but it seems i cannot figure it out.
I run R x64 3.2.6. I know it is not the latest version, but it should not
give me unexpected results because of that i would think.
sessionInfo()
R version 3.6.2 (2019-12-12)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] compiler_3.6.2
Thanks,
Monica
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.