Home > Enterprise >  How to create an if/else statement in R based on an open file condition?
How to create an if/else statement in R based on an open file condition?

Time:10-11

I've created this function to open a file in R:

openfasta<-function(DNAseq){
  DNASeq <- readline(prompt = "Enter the .fasta file name:")
  readLines(DNASeq)

Now if the file can not be found in the working directory, the script must output a warning message and ask for the file name repetitively until the file is located.

I tried this, but it didn't work:

if (DNASeq) {
  return()
  }
  else {
    cat(DNASeq <- readline(prompt = "Enter the .fasta file name:"))
  }
}

I think if a For loop would be a reasonable solution too.

CodePudding user response:

You can use a while loop to check for file existence. If not found use a print statement to display a warning and prompt again.

openfasta <- function(DNAseq){
   while(!file.exists(DNAseq)){
        print("The file you requested was not found.")
      
        DNASeq <- readline(prompt = "Enter the .fasta file name:")
    }
  readLines(DNASeq)
  }
  • Related