Reputation: 37
I have the following code:
pdf=function(x) {
if (x<=1 && x>2) 0
else if (1.5>x && x>1) (4*(x-1))
else (x>=1.5 && x<=2) (4*(2-x))
}
Where I'm attempting to create a function of a probability density function and calculating the density at x= 1.25
, x=1.75
, x=1.95
. It runs through with no problem and calculates the first value of x=1.25
. However, when attempting to calculate the values x=1.75
and x=1.95
, it returns with the error message:
Error in (x >= 1.5 && x <= 2)(4 * (2 - x)) : attempt to apply non-function
Any help would be greatly appreciated.
I've already attempted to remove the brackets around (4*(x-1))
and (4*(2-x))
, both don't solve the issue and the latter returns the error of an unexpected numeric constant.
Upvotes: 0
Views: 430
Reputation: 76402
Here are two vectorized ways, one with ifelse
, the other with logical indices.
pdf <- function(x) {
ifelse(x <= 1 | x > 2, 0,
ifelse(1 < x & x < 1.5, 4*(x - 1), 4*(2 - x)
)
)
}
pdf2 <- function(x){
i <- 1 < x & x < 1.5
j <- 1.5 <= x & x <= 2
y <- rep(0, length(x))
y[i] <- 4*(x[i] - 1)
y[j] <- 4*(2 - x[j])
y
}
X <- seq(-1, 3, by = 0.1)
identical(pdf(X), pdf2(X))
#[1] TRUE
Upvotes: 0
Reputation: 1379
Your issue is, that else
does not use a conditional statement, and is only ever executed if all other if
statements are false
.
You have to add an else if
statement to your final else
, so that the conditional is actually used.
Edit: As @Shree pointed out in the comments, your initial if
statement will never be reached, and should be an OR
operator rather than an AND
pdf=function(x) {
if (x<=1 || x>2) 0
else if (1.5>x && x>1) (4*(x-1))
else if (x>=1.5 && x<=2) (4*(2-x))
}
As pointed out by @Tim Biegeleisen in the comments, the final else if
may not particularly be necessary, and you can do the following instead
pdf=function(x) {
if (x<=1 || x>2) 0
else if (1.5>x && x>1) (4*(x-1))
else (4*(2-x))
}
Upvotes: 3