[R] Unexpected behavior from which.max (or possibly max)
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Sep 15 19:15:05 CEST 2011
On 15/09/2011 10:40 AM, Jason Curole wrote:
> Hi all,
>
> I was recently writing a script to identify the value and id of the maximum
> observation in a sliding window when I ran into some unexpected behavior. I
> have included an example.
>
> > test<- c()
> > test$elev<- c(1:200)
> > test$i<- 1
> > test$window<- 10
>
> The following works for me:
>
> > check.max<- function(x){obs.max<- x$elev[x$i:x$i+x$window]; obs.max}
> > check.max(test)
> [1] 11
>
> But then which.max doesn't seem to honor x$i+x$window:
>
> > check.max<- function(x){obs.max<- which.max(x$elev[x$i:x$i+x$window]);
> obs.max}
> > check.max(test)
> [1] 1
>
> If I enclose x$i+x$window in parentheses it works:
>
> > check.max<- function(x){obs.max<- which.max(x$elev[x$i:(x$i+x$window)]);
> obs.max}
> > check.max(test)
> [1] 11
>
>
> What am I missing?
Operator precedence. You had
x$i:x$i+x$window
but consider this:
1:1+5
The : has higher precedence than the +, so that gives 6. Yours gives
x$i+x$window
Duncan Murdoch
> Here is sessionInfo (I know I need to upgrade; I am behind the state's
> McAfee firewall thingy which makes it very difficult for me):
>
> > sessionInfo()
> R version 2.11.1 (2010-05-31)
> x86_64-pc-linux-gnu
>
> locale:
> [1] LC_CTYPE=en_US.utf8 LC_NUMERIC=C
> [3] LC_TIME=en_US.utf8 LC_COLLATE=en_US.utf8
> [5] LC_MONETARY=C LC_MESSAGES=en_US.utf8
> [7] LC_PAPER=en_US.utf8 LC_NAME=C
> [9] LC_ADDRESS=C LC_TELEPHONE=C
> [11] LC_MEASUREMENT=en_US.utf8 LC_IDENTIFICATION=C
>
> attached base packages:
> [1] stats graphics grDevices utils datasets methods base
>
> loaded via a namespace (and not attached):
> [1] tools_2.11.1
>
> Thanks, Jason
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
More information about the R-help
mailing list