Home > Mobile >  Build a function out of an algorithm in R
Build a function out of an algorithm in R

Time:10-09

I have built an algorithm in R to check if an integer a is a divisor of an integer b, but I don't know how to make a function out of it.

print("We are going to evaluate if an integer a is a divisor of an integer b.");

i = TRUE;
while(i == TRUE){
  a = as.numeric(readline(prompt = "Enter an integer a: "));
  if(is.na(a) == TRUE){
    print("Enter valid data: ");
  }
  else{
    if(a%%1 != 0){
      print(paste(a,"is not an integer. Enter valid data: "));
    }
    else{
      i = FALSE;
    }
  }
}

j = TRUE;
while(j == TRUE){
  b = as.numeric(readline(prompt = "Enter an integer b: "));
  if(is.na(b) == TRUE){
    print("Enter valid data: ");
  }
  else{
    if(b%%1 != 0){
      print(paste(b,"is not an integer. Enter valid data: "));
    }
    else{
      j = FALSE;
    }
  }
}

if(b%%a == 0){
  print(paste(a,"is a divisor of",b,"."));
}else{
  print(paste(a,"is not a divisor of",b,"."));
}

CodePudding user response:

As @r2evans mentioned wrapping the code in func <- function() {..} should do it. Another tip, don't use condition == TRUE or condition == FALSE in code. To check for TRUE values you can use condition as it is and for FALSE use !condition.

can_a_divide_b <- function() {
  print("We are going to evaluate if an integer a is a divisor of an integer b.");
  
  i = TRUE;
  while(i){
    a = as.numeric(readline(prompt = "Enter an integer a: "));
    if(is.na(a)){
      print("Enter valid data: ");
    }
    else{
      if(a%%1 != 0){
        print(paste(a,"is not an integer. Enter valid data: "));
      }
      else{
        i = FALSE;
      }
    }
  }
  
  j = TRUE;
  while(j == TRUE){
    b = as.numeric(readline(prompt = "Enter an integer b: "));
    if(is.na(b) == TRUE){
      print("Enter valid data: ");
    }
    else{
      if(b%%1 != 0){
        print(paste(b,"is not an integer. Enter valid data: "));
      }
      else{
        j = FALSE;
      }
    }
}

if(b%%a == 0){
  print(paste(a,"is a divisor of",b,"."));
}else{
  print(paste(a,"is not a divisor of",b,"."));
}
}

You may call the function as following -

can_a_divide_b()
#[1] "We are going to evaluate if an integer a is a divisor of an integer b."
#Enter an integer a: 2
#Enter an integer b: 10
#[1] "2 is a divisor of 10 ."
  • Related