Home > Blockchain >  Is the all( ) function related to the for( ) function in R?
Is the all( ) function related to the for( ) function in R?

Time:11-16

I was given a task of creating a function that checks if a natural number is prime or not without the use of the for() function. That I solved by defining a "set" and using the all() function.

prime <- function(nat){
  N <- 1:(nat-1)
  N <- N[-c(1,nat)]
  if(!isTRUE(all(nat%%N != 0))){
    return(paste(nat,"is a prime number."))
  }else{
    return(paste(nat,"is not a prime number."))
  }
}
#Assuming the input is actually a natural number. Error response is not my issue.

Now, my question is if the all() function is actually not a for() "in disguise". It is basically doing the same task the for() function would have done. Checking the logical statement of nat%%N != 0 for each member of my "set". I'm not an expert, but it seems to me that the all() function is a for() function for logical values and therefore, their inner workings must be very similar.

If someone could provide clarification as to whether the all() function works in the same way as a for() function or not I would appreciate it. Can the all() be considered a for() function?

CodePudding user response:

In one sense, any function that operates on a vector of length greater than 1 can be represented as a for loop. For example, consider sum(), which computes the sum of the elements of the given vector. It could be represented as the following:

sum <- function(x) {
  s <- 0
  for (i in x) s <- s   i
  s
}

Indeed, in the C code underlying R, it my actually be represented in this way. Do you consider sum() to be a for loop? If not, all() can be represented as a sum:

all <- function(x) {
  sum(as.logical(x)) == length(x)
}

It is clearly not a for loop in this case. If your assignment is to avoid using the for function, then anything you write that avoids for should be fine.

  • Related