Reputation: 51
I am trying to use elements from a vector to conduct if-then statements, but for some reason, I keep running into the following error:
"Error in if (xd[2] <= a) { : missing value where TRUE/FALSE needed"
I am not sure why this keeps coming up, as the only thing that is different with that line of code seems to be that I am using xd[2] instead of xd[1]. I get my desired results with xd[1] but not xd[2]. The conditional seems to be met as well.
reset1 = {
a = 0.3 #lower bound of belief
b = 0.9 #upper bound of belief
A = 5
w = c(1,2)
xd = c(1,2)
w[1] = 5 #cost of abatement/effort for Driver1
xd[1] = 0.3
w[2] = 3 #cost of abatement/effort for Driver2
xd[2] = 0.3
expfine1 = function(xd,A,a,b){if(xd[1]<=a){A} else if(a<xd[1] & xd[1]<b){(((b-xd[1])/(b-a))*A)} else if(xd[1]>b){0}}
expfine1(xd[1],A,a,b)
expcost1 = function(xd){proba1(xd[1])*expfine1(xd[1],A,a,b)}
expcost1(xd[1])
expfine2 = function(xd,A,a,b){if(xd[2]<=a){A} else if(a<xd[2] & xd[2]<b){(((b-xd[2])/(b-a))*A)} else if(xd[2]>b){0}}
expfine2(xd[2], A, a, b)
expcost2 = function(xd){proba2(xd[2])*expfine2(xd[2],A,a,b)}
expcost2(xd[2])
Upvotes: 1
Views: 56
Reputation: 42544
From OP's code and Tim's accepted answer I understand that the OP wants to create a function which interpolates linearly on the interval [a, b] and is constant outside of the interval.
For the sake of completeness, there is the approxfun()
function in base R which returns "a function performing the linear (or constant) interpolation":
expfine <- approxfun(c(a, b), c(A, 0), rule = 2L)
This function can be call with a vector of x
values:
expfine(c(0.2, 0.3, 0.4, 0.8, 0.9, 1.0))
[1] 5.0000000 5.0000000 4.1666667 0.8333333 0.0000000 0.0000000
Note that there is a difference to OP's function definitions which are undefined for x == b
. I guess that this happened inadvertently. I believe the intervals should be right closed consistently. Also note, that Tim's implementation explicitely returns NA
for x == b
.
The function can be plotted
plot(expfine)
Upvotes: 0
Reputation: 520878
You should be using the ifelse()
function, which is vectorized:
expfine1 <- function(xd,A,a,b) {
ifelse(xd <= a, A,
ifelse(a < xd & xd < b, A*(b-xd) / (b-a),
ifelse(xd > b, 0, NA)))
}
expfine1(xd,A,a,b)
Upvotes: 1