Reputation: 1
I have tried to define this function with RStudio but im having a lot of problems and cant understand whats wrong
x <- seq(-10, 10, 0.001)
fx <- function()
if(x < 0 ) {fx<- sin(x)
}
else if (x >= 0 && x < 2)
{
fx<- x^2
}
else if(x >= 2 )
{
fx<- 4*exp(x-2)
}
}
plot(x, fx)
How could i do this? I can't find anything useful on the internet
Upvotes: 0
Views: 1370
Reputation: 24252
A solution using Vectorize
:
x <- seq(-2, 1, 0.001)
f <- function(x) {
if(x<0) {
fx <- sin(x)
} else if (x >= 0 && x < 2) {
fx <- x^2
} else if(x >= 2 ) {
fx <- 4*exp(x-2)
}
fx
}
f <- Vectorize(f)
plot(x, f(x))
Upvotes: 0
Reputation: 124083
Try this:
x <- seq(-10, 10, 0.001)
fx <- function(x) {
if (x < 0) {
return(sin(x))
} else if (x >= 0 & x < 2) {
return(x^2)
} else {
return(4*exp(x-2))
}
}
plot(x, sapply(x, fx))
Created on 2020-04-11 by the reprex package (v0.3.0)
Upvotes: 0
Reputation: 18683
Your function shouldn't be using if
for vectors. Best to us ifelse
, or just utilise R's vector capabilities:
fx <- function(x){
f <- NULL
f[x<0] <- sin(x[x<0])
f[x>=0 & x<2] <- x[x>=0 & x<2]^2
f[x>=2] <- 4*exp(x[x>=2] - 2)
f
}
x <- seq(-10, 3, 0.01)
plot(x, fx(x), type="l", las=1)
Upvotes: 3