Gabelins Gabelins - 2 months ago 24
R Question

printing warnings by R

I have a code on a file that works on a matrix and I read it by using


source("filecode.r")


As the matrix that the code works with must have some specific characteristics, I would like to print a message to remember the user that the input matrix must be formatted with those characteristics.

The code is this:

n<- nrow(aa)
d_ply(aa, 1, function(row){
cu<- dist(as.numeric(row[-1]))
cucu<- as.matrix(cu)
saveRDS(cucu, file = paste0(row$ID, ".rds"))
}, .progress='text', .print = TRUE)


Ideally I would like to add a warning message appearing before the code starts running...like this:

Warning(“1) did you write ‘ID’ in position [1,1] of the input matrix?;
2) is your matrix saved as a .txt?
3) ensure that the matrix file does not have empty rows at the end”)


and receiving also a question like "do you want to go on then?".
Thank you in advance for all suggestions!
Gab

Answer

Put that at the beginning of your file:

check <- readline(prompt="Warning!\n(1) did you write 'ID' in position [1,1] of the input matrix? \n(2) is your matrix saved as a .txt?\n(3) ensure that the matrix file does not have empty rows at the end\n\n Do you wish to continue? (y/n)")
if(check == "n") stop("Aborted.")
print(check)  #Here would follow your code instead

If you type "y" the following code will be evaluated. If you type "n", the script stops and print the message inside stop().

enter image description here


You could also make sure that only 'y' and 'n' are accepted by putting the prompt statement inside of a while loop:

check <- NA
while(!(check %in% c('y','n'))) {
  check <- readline(prompt="Warning!\n(1) did you write 'ID' in position [1,1] of the input matrix? \n(2) is your matrix saved as a .txt?\n(3) ensure that the matrix file does not have empty rows at the end\n\n Do you wish to continue? (y/n)")
}
if(check == "n") stop("Aborted.")
Comments