Reputation: 11
I keep getting the following error.
Error in as.vector(x, mode) :
cannot coerce type 'closure' to vector of type 'any'
I want to plot f2(x) versus x using the matplot option in RStudio. Is there something I'm missing?
f2<-function(x){
if(x>=0){
return(sqrt(x))
}else{
return(sqrt(-x))
}
}
x<- seq(from= -5, to= 5, by= 0.001)
require(graphics)
matplot(f2, x, type = "1", xlab = expression(alpha), ylab = expression(sqrt(abs(alpha))))
Upvotes: 1
Views: 2292
Reputation: 887108
The function f2
was not applied on 'x'. Having said that, if/else
would not be efficient here as it is not vectorized and we may need to loop if we need to apply. Instead another function with ifelse
or within in the function create a logical index and replace the original vector based on the index
f1 <- function(v) {
i1 <- v >= 0
v[i1] <- sqrt(v[i1])
v[!i1] <- sqrt(-v[!i1])
v
}
matplot(f1(x), type = "l", xlab = expression(alpha),
ylab = expression(sqrt(abs(alpha))))
Upvotes: 1