r - if x>0 use f(x) ,if x<0 use g(x) and plot all y in one plot -


how write function chooses between 2 functions depending on whether argument larger or smaller 0 , writes generated values y vector 1 can plot(x,y). can please tell me whether right ansatz or not:

x <- runif(20,-20,20) y <- numeric() f <- function(x){           if(x>0){y <- c(y,x^2)}     if(x<0){y <- c(y,x^3)}     } for(i in x){f(x)} plot(x,y) 

as can see, there few problems code:

  1. your function f not return meaningful values. assignment y not global , remains in scope of function.

  2. many operations in r vectorized (i.e. performed on whole vectors instead of individual elements), , important feature of r code, code not take advantage of that. give gist, when x > 0, , x vector, return boolean vector condition checked every element of x. when x^2, returns numeric vector every element square of corresponding element in x. ifelse vectorized operator, checks condition every element in vector. knowing that, can rid of function , loop , y <- ifelse(x<0,x^3,x^2).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -