1

I have a problem with a in if statement. I get an error message saying "absent value where TRUE / FALSE is required". I am trying to calculate a new variable using an if statement and a for cycle, but the data has NA values and the cycle I used cannot work any further after finding a NA value.

This is the variables I am using to create the new variable:

x=c(3,3,3,2,NA,2,3,NA,3,NA)
y=c(3,6,5,4,NA,3,2,NA,3,NA)
h=c(1,2,1.6666667,2,NA,1.5,0.6666667,NA,1,NA)

This the code I am using that has the problem with NA value:

z=rep(NA,length(y))
for(i in 1:length(x)){
if((x[i]==0 & y[i]>=3) | h[i]>=3){
  z[i]=1
} else if((x==0 & y[i]<3) | h[i]<3){
  z[i]=0
}
}

Can you tell me how could I include the NA values into the if statement or what should I do? Thanks for your reply.

  • You have two: one repeated warning (because you test `x==0` instead of `x[i]==0`), see https://stackoverflow.com/q/14170778/3358272, https://stackoverflow.com/q/14170778/3358272; and an error due to `NA` in your data, see https://stackoverflow.com/q/7355187/3358272 – r2evans Mar 02 '21 at 15:27

2 Answers2

1

We can make changes based on the NA by inserting is.na

for(i in 1:length(x)){
  if((x[i] %in% 0 & y[i]>=3 & !is.na(y[i])) | h[i]>=3 & !is.na(h[i])){
   z[i]=1
} else if((x[i] %in% 0 & y[i]<3 & !is.na(y[i])) | h[i]<3 & !is.na(h[i])){
   z[i]=0
    }
}
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You can check with !is.na(). Also this operation is vectorized so you don't need for loop.

inds <- x == 0 & y >= 3 | h >= 3
as.integer(inds & !is.na(inds))
#[1] 0 0 0 0 0 0 0 0 0 0

None of the value match the condition here.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213