[R] custom function that plots other functions- problem
Rui Barradas
ruipbarradas at sapo.pt
Sun May 5 19:53:43 CEST 2013
Hello,
Try the following. Note that argument 'how_many' is not needed, it can
be derived from the length of the functions vector.
plotter<- function(f, range, quality){
x <- seq(range[1], range[2], quality)
y <- sapply(seq_along(f), function(.i) f[[.i]](x))
plot(x, y[, 1])
for(i in seq_along(f)[-1]){
lines(x, y[, i], col = i) # argument 'col' added
}
}
plotter(c(sin, cos), c(0,2*pi), .02)
Hope this helps,
Rui Barradas
Em 05-05-2013 15:16, Bartłomiej Drążczyk escreveu:
> Hi everyone!
>
> Could you please help me with the following assignment? My aim is to write
> a custom function that draws the plots of functions submitted by the user.
> The catch is, that we do not know the exact number of functions the user
> will select to draw.
>
> The program is relatively easy with one function, f.e sin:
>
> mf<- function(f,range,quality){
>
> x<- seq(range[1],range[2], quality);
>
> y<- f(x);
>
> plot(x,y);
> }
>
> mp(sin, c(0,2*pi), .02);
>
> but I encountered some problems while trying to provide more than one- the
> following structure generates mistakes:
>
> plotter<- function(f,howmany,range,quality){
> x<-seq(range[1],range[2],quality)
> y<- matrix(f,how_many)
> plot(x,y[1,])
> for(i in 2:how_many){
> lines(x,y[i,])
> }
> }
>
> plotter<-(c(sin(x),cos(x)),2,c(0,2*pi),.02)
>
> I would really appreciate your help with this program.
>
> Regards,
> Bartek
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list