[R] Strange subvector output --> x[n] != x[1:n][n]

Patrick Burns pburns at pburns.seanet.com
Fri Dec 20 21:19:24 CET 2013


You've found an interesting corner of Circle 1
of 'The R Inferno'.

http://www.burns-stat.com/documents/books/the-r-inferno/

The issue is that your 'n' in the final case is
slightly less than 11.  So:

 > n
[1] 11
 > as.integer(n)
[1] 10
 > 1:n
  [1]  1  2  3  4  5  6  7  8  9 10 11

The mystery to me is why `:` thinks it is doing
an integer sequence but ends in 11 rather than 10.

Most people are likely to think the mystery is
why as.integer(n) is 10.  The reason is that coercion
to integer is truncation (except if the number is
really close to the integer farther from 0).  Why that
and not round?  Well, just because.  (Actually probably
speed back in the day when it could matter.)

Pat


On 20/12/2013 04:33, Gewart wrote:
> Hi, Can anyone explain what is going on...!?   For a vector
> "x=seq(min,max,0.01)", when generating sub-vector "a" based on a starting
> value "st", things go as expected as long as "st" is not too close to the
> beginning of "x".  For example, if x starts at -5 and increments by 0.01,
> whenever I try to generate the sub-vector "a" (as below) with a starting
> value of 0.49 or less it does not generate the expected output: The initial
> value of "a" is wrong.
>
> Thanks in advance for any clarity you can shed.
> Gary
>
> ...(please see two versions of code below)....
>
> #THIS WORKS...(st > -4.9)
>
> 	min = -5; max = 1;  x=seq(min,max,0.01)
>
> 	st= -4.8 ; end= 0
>
> 	a=x[((st-min)/0.01+1):((end-min)/0.01+1)]
> 	
> 			n=(st-min)/0.01+1
> #compare	
> 	a[1:10]; c(x[n:(n+9)])
>
> #test...
> 	n
> 	x[1:n]; x[n]           ### x[n]== x[1:n][n] ; As expected
> ##########################################################
> #  BUT THIS IS WEIRD!!...(st <= -4.9)
> 	
> 	st= -4.90 ; end= 0     ### -> BUG in generation of a!!
>
> 	a=x[((st-min)/0.01+1):((end-min)/0.01+1)];
> 	
> 			n=(st-min)/0.01+1
> #compare	
> 	a[1:10]; c(x[n:(n+9)])
> #test
> 	n
> 	x[1:n]; x[n]  ### NOW x[n] != x[1:n][n]   !!?? What is going on!?
>
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Strange-subvector-output-x-n-x-1-n-n-tp4682526.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>

-- 
Patrick Burns
pburns at pburns.seanet.com
twitter: @burnsstat @portfolioprobe
http://www.portfolioprobe.com/blog
http://www.burns-stat.com
(home of:
  'Impatient R'
  'The R Inferno'
  'Tao Te Programming')



More information about the R-help mailing list