# le istruzioni che seguono f <- function(x) ifelse(x > 1, 2*x-1, x^2) Df <- function(x) eval(D(body(f),"x")) plot(Df,-2,2) # fanno apparire un messaggio di errore in quanto R non # calcola la derivata in cui compare un ifelse # Se vogliamo esprimere la funzione mediante un'unica # assegnazione possiamo provvedere così: f1 <- function(x) 2*x-1; f2 <- function(x) x^2 f <- function(x) ifelse(x > 1, f1(x), f2(x)) plot(f,-3,3,ylim=c(-2,5),col="blue") abline(v=axTicks(1),h=axTicks(2), col="violet",lty=3) abline(v=0,h=0,lty=2,col="brown") Df1 <- function(x) eval(D(body(f1),"x")) Df2 <- function(x) eval(D(body(f2),"x")) Df <- function(x) ifelse(x > 1, Df1(x), Df2(x) ) curve(Df,add=TRUE,col="red") # Alternativa possibile alle righe precedenti Df1 <- ... e Df2 <- ... Der <- function(f) eval(D(body(f),"x")) Df1 <- function(x) Der(f1); Df2 <- function(x) Der(f2)