Andi92 Andi92 - 1 year ago 40
R Question

curve() works in the first example but not the second, but they look identical. Why?

I'm new to R and try to do some exercises. I wonder why the first code works fine while the second code doesn't. When I try to run the second code, it says he can't find function

a
.

1.)

x = seq(from = - 9, to = 9, len = 100)
curve(dnorm(x,0,2),add = FALSE, from = -9, to = 9)


2.)

x = seq(from = - 9, to = 9, len = 100)
a = dnorm(x,0,2)
curve(a,add = FALSE, from = -9, to = 9)

Answer Source

The use of curve is always puzzling. Look at ?curve on its first argument expr, as well as the "Details" section.

In fact, you misunderstood the first (working) case.

curve(dnorm(x, 0, 2), from = 9, to = 9)

does not use the x you gave: seq(-9, 9, length = 100), but choses sampling points internally. See argument n of curve. Here, you are passing curve a function of formal argument x, not a real-valued vector, as a in your second (failing) case.

If you don't believe this, let's change line displaying to point displaying:

curve(dnorm(x, 0, 2), n = 10, from = -9, to = 9, type = "p")

You see? There are only 10 points on the graph, even if you have preset x <- seq(-9, 9, len = 100).

Another supplementary example is to tweak with xname. Let's use another variable, say foo.

curve(dnorm(foo, 0, 2), from = -9, to = 9, xname = "foo")

There is no variable foo in this R session, but the above code works. Because xname tells curve that foo is a formal variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download