Conditional looping

Hello again R family, Please I have another problem, which ought to have a simple solution, but I am not able to figure it out. I have written a function, which should loop through my data and return either the highest or lowest figure depending on whether or not a condition is specified. Below is my code:

rangeFinder <- function(data,max_finder = TRUE ){
  
  show <- ifelse(max_finder,
    
    for(i in 1:ncol(data)){
    result <- max(data[i])
    print(paste(result,"is the highest figure in",colnames(data[i])))
  
   },
  for(i in 1:ncol(data)){
     result <- min(data[i])
     print(paste(result,"is the lowest figure in",colnames(data[i])))
     
    }
  )
  return(show)
}

When I run each For loop independently, they work, but after adding the If statement and setting the argument max_finder to TRUE, I get the following result, along with the error message:

[1] "79 is the highest figure in AGE"
[1] "52 is the highest figure in ADDRESS"
[1] "1070 is the highest figure in INCOME"
[1] "4 is the highest figure in INCCAT"
[1] "100 is the highest figure in CAR"
[1] "56 is the highest figure in EMPLOY"
Error in ans[ypos] <- rep(yes, length.out = len)[ypos] : 
  replacement has length zero
In addition: Warning message:
In rep(yes, length.out = len) : 'x' is NULL so the result will be NULL

And when I set max_finder to FALSE, I get a 0.
I know I could use the apply function, but I want the result printed like a statement, which is why I have written my own algorithm, which is not working well yet.
Please as always, I will be grateful for any suggestions. Thanks!

There are a few things working against you here. The ultimate cause of your error, however, is that ifelse is trying to return a print action out of ifelse. But print doesn't return anything, so what you're actually returning is NULL.

Unfortunately, R wants the result from ifelse to have the same length as max_finder, so it is complaining about return a zero length result into an object that should have a length of one.

This can be avoided by recognizing that ifelse isn't the correct mechanism to use for what you are doing here. ifelse will perform an if-else operation over a vector, but presumably, max_finder is a single value for flow control. In cases of flow control, you're better off with if ( ) { } else {}. Consider the following:

rangeFinder <- function(data,max_finder = TRUE ){
  
  if (max_finder){
    for(i in 1:ncol(data)){
      result <- max(data[i])
      print(paste(result,"is the highest figure in",colnames(data[i])))
    }
  } else {
    for(i in 1:ncol(data)){
      result <- min(data[i])
      print(paste(result,"is the lowest figure in",colnames(data[i])))
      
    }
  }
}
1 Like

Hi, thanks for your suggestion; the algorithm now works fine.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.