I would want to draw a plot of an function that
if 0< x< 0.5, f(x)= 0.5(x)^3*(1-x)^6
if 0.5≤ x< 1 , f(x)= 1.5(x)^3*(1-x)^6
if x=0 or x=1, f(x)=0.
How could I do this?
Here is a function that is fully vectorized and returns NA
outside the interval [0, 1]. It utilizes that logical values are coerced to 0/1 in arithmetic operations and that anything to the power of zero is one.
foo <- function(x) ((x > 0 & x < 0.5) * 0.5 * x ^ 3 * (1 - x) ^ 6 +
(x >= 0.5 & x < 1) * 1.5 * x ^ 3 * (1 - x) ^ 6) * NA ^ (x < 0 | x > 1)
curve(foo(x), -0.1, 1.1)
If possible it is better to use a vector input to the function:
foo <- function(x) ifelse(x>0 & x<0.5, 0.5*x^3 *(1-x)^6, 1.5*x^3 *(1-x)^6)
plot(foo, from=-0.1, to=1.1)
myf=function(x) {
if (x>0 & x<0.5) {
return(0.5*x^3*(1-x)^6)
} else if (x>=0.5 & x<1) {
return(1.5*x^3*(1-x)^6)
} else {
return(0)
}
}
myrange=seq(0,1,0.01)
plot(y=sapply(myrange,myf),x=myrange,type="l")
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.