Strange Error in if/conditional statement

Hi there,

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])

Your expfine2 function starts with

expfine2 = function(xd,A,a,b)

so inside of the function xd will refer to whatever is passed to that parameter. You then call the function with

expfine2(xd[2], A, a, b)

so xd within the function refers to the single value of xd[2]. When you attempt the comparison

a < xd[2]

xd[2] returns NA. This would be easier to think about if you started the definition of your function with

expfine2 = function(K, L, M, N)

If you pass xd[2] to K, then K[1] returns the value of xd[2] and K[2] returns NA. Here is an example with no function involved.

xd <- c(3, 9)
TEST <- xd[2]  
TEST[1]
#> [1] 9
TEST[2]
#> [1] NA

Created on 2020-02-21 by the reprex package (v0.2.1)

3 Likes

Thank you for your detailed explanation! It was very helpful

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.