Using “curve” to plot a function: a tricky expression?

别说谁变了你拦得住时间么 提交于 2019-12-02 03:41:25

问题


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



来源:https://stackoverflow.com/questions/51033306/using-curve-to-plot-a-function-a-tricky-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!