Using “curve” to plot a function: a tricky express

2019-02-27 12:56发布

问题:

My question concerns something that should be fairly simple, but I can't make it work. What I mean is you can calculate x and y and then plot them with the plot function. But can this be done using the curve function?

I want to plot the following R function f2:

n <- 1
m <- 2
f2 <- function(x) min(x^n, x^(-m))

But this code fails:

curve(f2, 0, 10)

Any suggestions?

回答1:

As has been hinted at, the main reason why the call to curve fails is because curve requires a vectorized function (in this case feed in a vector of results and get out a vector of results), while your f2() function only inputs and outputs a scalar. You can vectorize your f2 on the fly with Vectorize

n <- 1
m <- 2

f2 <- function(x) min(x^n, x^(-m))
curve(Vectorize(f2)(x), 0, 10)


回答2:

You need to use vectorised pmin instead of min (take a look at ?pmin to understand the difference)

f2 = function(x, n = 1, m = 2) {
    pmin(x^n, x^(-m))
}

curve(f2, from = 0, to = 10)

On a side note, I would make n and m arguments of f2 to avoid global variables.


Update

To plot f2 for different arguments n and m you would do

curve(f2(x, n = 2, m = 3), from = 0, to = 10)



回答3:

Is the curve function needed or would this work?

n <- 1 # assumption
m <- 2 # assumption

f2 <- function(x) min(x^n, x^(-m))

x.range <- seq(0, 10, by=.1) 
y.results <- sapply(x.range, f2) # Apply a Function over a List or Vector
# plot(x.range, y.results) old answer
plot(x.range, y.results, type="l") # improvement per @alistaire