0

What's the easiest way to plot a function of multiple variables in a 2D graph by giving some of the input parameters a value. Let's consider a simple example

my.function<-function(a,b,x){a*x^2+b}

Now I want to plot the simple parabola where a=1 an b=0 . So I define a new function: new.function<-function(x){my.function(1,0,x)}; plot(new.function) .

Is there any way where I can plot the function without defining new.function?

Normally I use Mathematica and in Mathematica it would be:

Plot[my.function[1,0,x],{x ... }]

2
  • 2
    Basically the same in R plot(function(x) { my.function(1,0,x) }) Commented May 7, 2017 at 14:24
  • 2
    Or you can use curve like curve(my.function(1, 0, x), from=0, to=10). Commented May 7, 2017 at 15:51

2 Answers 2

1

For future readers, I am sharing @G5W 's comment as answer in here:

plot(function(x) { my.function(1,0,x) })

I believe this is the best way of those provided in here

Sign up to request clarification or add additional context in comments.

Comments

1

You should not need to define a new function. You can use the original function, my.function, and pass in x-values 1 through 10 to plot the parabola:

my.function <- function(a,b,x){a*x^2+b}
x <- 1:10
y <- my.function(a=1,b=0,x=x)
plot(y~x)

2 Comments

The function is vectorized, so no need for sapply. y <- my.function(a = 1, b = 0, x = 1:10) works fine.
Thanks for pointing that out. I edited my post. It's much more simple without sapply().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.