I'm trying to plot this function in R
f <- function(a,b,c,x){
if(a<=x){
return(c*x)}
if(x<=b){
return(-c*x)}
return(0)}
but when I try to plot it with:
a<-0
b<-6
c<-3
curve(f(a,b,c,x), xlim=c(0,6), ylim=c(0,3), col='blue', lwd=3, add=FALSE)
I get:
Warning message in if (a <= x) {:
“the condition has length > 1 and only the first element will be used”
Any help please?
Your function f
can't operate with vectors for x
since the condition (a <= x)
isn't straight forward to evaluate for a vector.
Let's take a look at
x <- -6:6
f(a,b,c,x)
Your function f
doesn't understand what to do with x
while evaluating
if (a <= x) { code }
so the first element of x
is always used.
So, what to do?
x <- -6:6
f_2 <- function(x) { sapply(x, function(x) f(a,b,c,x)) }
curve(f_2, xlim=c(-6,6), ylim=c(0,20), col="blue", lwd=2, add=FALSE)
We define a new function f_2
. sapply
takes one element of x
and uses it with f(a,b,c,x)
than uses the next element etc. This function works with vectors x
as input.
Compare it to
curve(f(a,b,c,x), xlim=c(-6,6), ylim=c(0,20), col="blue", lwd=2, add=FALSE)
for better understanding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.