[R] custom function gives unexpected result - for me
Monica Palaseanu-Lovejoy
mon|c@p@|@|ovejoy @end|ng |rom gm@||@com
Sat Apr 18 02:49:22 CEST 2020
Hi,
I cannot believe I did that. Usually I remember to add parenthesis but this
time obviously I didn’t. Thank you all so much for answering so quickly.
Thanks,
Monica
On Fri, Apr 17, 2020 at 7:06 PM Peter Langfelder <peter.langfelder using gmail.com>
wrote:
> You need 1:(m-1) in your function. The operator : has precedence over -:
>
> > 1:3-1
> [1] 0 1 2
> > 1:(3-1)
> [1] 1 2
>
> Happened to me a few times as well before I remembered.
>
> HTH,
>
> Peter
>
> On Fri, Apr 17, 2020 at 3:50 PM Monica Palaseanu-Lovejoy
> <monicapalalovejoy using gmail.com> 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
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help using 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.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list