Skip to content

Instantly share code, notes, and snippets.

@RamiKrispin
Created September 16, 2022 14:14
Show Gist options
  • Save RamiKrispin/6bdbb6e155e454ef4d00f357c75e3996 to your computer and use it in GitHub Desktop.
Save RamiKrispin/6bdbb6e155e454ef4d00f357c75e3996 to your computer and use it in GitHub Desktop.
Examples for printing messages during run time with R
# Print messages with print and cat
print("This is the message I want to print")
cat("This is the message I want to print\n") # Using the \n operator to jump for the next line
# The print command can also print code output
print(data.frame(x = 1:3, y = 4:6))
# Where cat cannot print non text or multiple vector objects
cat(data.frame(x = 1:3, y = 4:6))
# Adding colors
# Using the crayon package
library(crayon)
cat(green("Process A ended successfully"))
cat(red("Process A failed"))
msg <- function(message, color = "green"){
if(color == "green"){
cat("\033[0;92m",message,"\033[0m\n")
} else if(color == "red"){
cat("\033[0;91m",message,"\033[0m\n")
} else {
cat(message, "\n")
}
}
msg("Process A ended successfully")
msg("Process A failed", color = "red")
# Using symbols
cat("\033[0;92m\xE2\x9D\x8C\033[0m\n")
cat("\033[0;92m\xE2\x9C\x94\033[0m\n")
# Adjust the message to the console width
fit_message <- function(message){
`%>%` <- magrittr::`%>%`
# Error handling
if(!is.character(message)){
stop("The input message is not string")
}
w <- getOption("width")
spaces <- base::gregexpr(pattern = " ", text = message)[[1]] %>%
as.numeric()
if (base::nchar(message) > w) {
for (i in 1:floor(nchar(message)/w)) {
r <- max(spaces[which(spaces <= w * i)])
substr(message, r, r) <- "\n"
}
}
return(cat(message))
}
my_long_message <- "I have a long message that I want to print during the run time without cutting words"
my_long_message
# using cat
cat(my_long_message)
#using the adjusted function
fit_message(my_long_message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment