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:
your function
f
not return meaningful values. assignmenty
not global , remains in scope of function.many operations in
r
vectorized (i.e. performed on whole vectors instead of individual elements), , important feature ofr
code, code not take advantage of that. give gist, whenx > 0
, ,x
vector, return boolean vector condition checked every element ofx
. whenx^2
, returns numeric vector every element square of corresponding element inx
.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
Post a Comment