質問

Consider the following problem: x is a numeric vector, pretty(x) (or labeling::extended() etc.) provides pretty breaks, to which I want to manually add some values. Now, x can take many forms, say c(3.20003, 3.20006) for the sake of example. pretty() is pretty smart at finding good breaks for the interval, 3.200030 3.200035 3.200040 3.200045 3.200050 3.200055 3.200060. Say, I want to add a break at pi, how many digits should I round it to, for consistency with the other values? (in this case, round(pi, 6) = 3.141593)

I thought of using nchar, plyr::round_any, but I can't think of a robust method that can handle all cases, including those with scientific formatting (1.3e-4) etc.

役に立ちましたか?

解決

Interesting question.

Assuming of course that your plotting function is using pretty() (or something that behaves like it) to determine axis breaks, this should provide a general-enough solution:

f <- function(x, range) {
    rcol <- floor(log10(abs(diff(pretty(range)[1:2]))))
    round(x, -rcol)
}

## Test it out
options(digits=15)
x <- c(3.20003, 3.20006)

f(pi, x)
# 3.141593

f(pi*1e3, x)
# [1] 3141.592654

f(pi*1e-3, x)
# [1] 0.003142

f(pi*1e10, x*1e10)
# [1] 31415930000

f(pi*1e20, x*1e20)
# [1] 3.141593e+20

f(pi, c(0,5))
# [1] 3

f(pi, c(0,10))
# [1] 3

f(c(pi, -pi), c(-1.2,0.0))
# [1]  3.1 -3.1

f(pi*1e-7, x)
# [1] 0

f(pi*2e-7, x)
# [1] 1e-06
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top