Damon C. Roberts
Damon C. Roberts

Reputation: 326

Ability to print a message in R console to indicate function is successful?

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?

Upvotes: 0

Views: 1805

Answers (2)

FrakTool
FrakTool

Reputation: 65

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.

Upvotes: 0

David T
David T

Reputation: 2143

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

Upvotes: 3

Related Questions