[R] Plotting own function

jim holtman jholtman at gmail.com
Tue Dec 7 13:55:54 CET 2010


You need to use 'ifelse' in this case since it will handle a vector
and 'if' is only for single values:

func <- function(x) {
       y <- exp(-0.5*((x-63.9)/23.2)^2)
       ifelse(x > 63.9, 2 - y, y)
}


x = seq(-10,150,length=500)
y <- func(x)
plot(x,y,type="l",lwd=2,col="red")



On Tue, Dec 7, 2010 at 6:57 AM, Tobias Schultze <webmaster at tubo-world.de> wrote:
> Hello,
> I have a simple question but didn't find a solution.
> How do I plot a custom function.
>
> I have defined this function
>
> func <- function(x) {
>        y <- exp(-0.5*((x-63.9)/23.2)^2)
>        if(x > 63.9)
>                return(2 - y)
>        else {
>                return(y)
>        }
> }
>
> and want to plot it in a specified range like
>
> x = seq(-10,150,length=500)
> y <- func(x)
> plot(x,y,type="l",lwd=2,col="red")
>
> But it doesn't work because it expects a vector but I need to compare the
> scalar x.
> How do I do it correctly?
>
> Thanks a lot
> Tobias
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list