0

I am trying to be more elegant in my coding and leveraging the apply functions. I wanted to stick one in a loop like so

for (ind in (ind2fix ))
{
  ADPPK[,ind] = mapply(categorize_cov,value = ADPPK[,ind-4], low = ADPPK[,ind-2],high = ADPPK[,ind-1],doserec = ADPPK$EVID)  
}

with the function defined as

categorize_cov <- function(value, low, high, doserec)
{  
  if (doserec == 0)
  {
    if (value > high)
      return("HIGH")
    else if (value < low )
      return("LOW")
    else
      return("NORMAL")
  }
  else
  {
    return(NA)
  }
}

I get the following error

Error in if (value > high) return("HIGH") else if (value < low) return("LOW") else return("NORMAL") : 
  the condition has length > 1

what is confusing is if I write it out rather than use indexing to specify the column it works as expected?

explicitly specifying the columns works but I have to do this like 20 times which is annoying

mapply(categorize_cov,value = ADPPK$GLU, low = ADPPK$GLUL,high = ADPPK$GLUH,doserec = ADPPK$EVID)  

Is there a way I can loop it ?

5
  • works for me. you might also want to use v <- Vectorize(categorize_cov) instead, then you can use v(...) like a function without mapply Commented Dec 15, 2024 at 5:24
  • 1
    value is an entire column. The R if function cannot handle entire columns. Commented Dec 15, 2024 at 5:36
  • @IRTFM But I do the same thing by explicitly stating the column and the code works. It only is failing when I use indices to reference the column Commented Dec 17, 2024 at 14:51
  • Without a minimal reproducible example we are not going to see this Q as worthy of further effort. We don’t know the structural aspects of your data. The error indicates the ‘if’ function has been given a longer object than it can handle. Commented Dec 17, 2024 at 16:17
  • OK I will make up a dataset Commented Dec 17, 2024 at 16:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.