0

say I have a simple function that I want to run in R. If the function runs successfully, I would like the R console to print a message similar to "Function Ran Successfully" and if it doesn't, R uses its normal error or warning messages to explain what is wrong with the function. Is there a way to do this?

  • 2
    `message("hello world")`? – r2evans May 13 '20 at 03:57
  • 1
    Does this answer your question? [Why is message() a better choice than print() in R for writing a package?](https://stackoverflow.com/questions/36699272/why-is-message-a-better-choice-than-print-in-r-for-writing-a-package) – Ian Campbell May 13 '20 at 04:06

2 Answers2

3

You can use message or cat or print. If you use message, someone else has the option of invoking your function wrapped with suppressMessages(). cat is going to print to the terminal no matter what. Also, you have to end cat with a \n if you want the CRLF.

Messages are printed in red.

message("Function Ran Successfully")
cat("Function Ran Successfully\n")

If you want colored messages, use the crayon package

cat(crayon::green$bold("Function Ran Successfully\n"))

print is particularly useful if you want to print out a structure, rather than just a single string.

print(head(iris, 2))
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
David T
  • 1,993
  • 10
  • 18
  • If the function fails, will it print the standard R error message or will I need to specify a message for the function failing with this? All I am looking to do is create a success message but not change anything about what R would put if it is wrong. – Damon C. Roberts May 13 '20 at 04:38
  • It depends on what you mean by 'fail'. If it fails by, say, dividing by 0, or taking the square root of a character string - yes, you'll get an error message of some flavor. If it fails by returning an empty data frame, (that you didn't want) you'll need to specify the message. I like to put my success messages in green. – David T May 13 '20 at 04:46
  • 1
    `crayon` is delivered as standard even with minimal install right? otherwise people without the package would get an error – jimmymcheung Oct 23 '22 at 02:46
  • 1
    @jimmymcheung - Yes, it's in the minimal install. I believe it's used for the red printing in `warning` – David T Nov 09 '22 at 00:59
0
fun <- function(num) {
  #code here

  num = as.integer(readline(prompt="Enter a number: "))

  if (num>0){ print("positive number")}
  else if (num<0){ print("negative number")}
  else { print("zero")}
}  
fun()

Run fun() and input a value in the console.

This is a example with nasted loop, maybe that is what you want if you are creating your own funtions (besides this word in other cases to), if not let me know and I will delete this answer.

FrakTool
  • 65
  • 1
  • 15