1
votes

I'm not that good in programming R, maybe somebody can help me. I used pretty() function on some histograms (for breaks=) but sometimes got an error. Further testing brought me to following results:

pretty(-1:1,n=20)

[1] -1.0 -0.9 -0.8 -0.7 -0.6 -0.5 -0.4 -0.3 -0.2 -0.1 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

That's what I expected, also with the following line of code

pretty(-26:71,n=18)

[1] -30 -25 -20 -15 -10 -5 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75

BUT - here comes the problem, following pretty() usage brought a complete wrong result (not even getting above zero)

pretty(-0.26:0.71,n=10)

[1] -0.35 -0.30 -0.25 -0.20

Can anybody explain to me what I'm doing wrong ? Thanks for your help !

2
Maybe you meant pretty(seq(-0.26, 0.71, .01), n=10). -0.26:0.71 is.equal to -.26 as : makes a sequence with a step size of 1.stefan

2 Answers

2
votes

The description of pretty from help(pretty) does a good job explaining the purpose:

Compute a sequence of about n+1 equally spaced ‘round’ values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10.

Your first call included the sequence -1:1:

-1:1
[1] -1  0  1

pretty(-1:1,n=20)
 [1] -1.0 -0.9 -0.8 -0.7 -0.6 -0.5 -0.4 -0.3 -0.2 -0.1  0.0  0.1  0.2
[14]  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1.0

You got some nice values that cover -1 to 1. The same is true for your second call.

However, your third call included the sequence -0.26:0.71. The following are equivallent:

-0.26:0.71
[1] -0.26
seq(-0.26,0.71,by = 1)
[1] -0.26

Since -0.26 and 0.71 are closer together than 1, you only get a single value returned.

Therefore, pretty(-0.26,n=10) makes a nice sequence around -0.26:

pretty(-0.26,n=10)
[1] -0.35 -0.30 -0.25 -0.20

Perhaps instead you'd prefer this:

pretty(c(-0.26,0.71),n=10)
 [1] -0.3 -0.2 -0.1  0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8

The code underlying pretty is somewhat complicated. But you can see the function by typing pretty.default at the console and reviewing the C source here.

1
votes

Another way of dealing with it is to multiply by 10 and then divide by 10 again.

 pretty((10*-0.26):(10*0.71), n=10)/10
 [1] -0.3 -0.2 -0.1  0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7