Skip to content

Instantly share code, notes, and snippets.

@lcomm
Last active March 31, 2016 02:23
Show Gist options
  • Save lcomm/1f68ce09559cf2b962fac1267173f1b0 to your computer and use it in GitHub Desktop.
Save lcomm/1f68ce09559cf2b962fac1267173f1b0 to your computer and use it in GitHub Desktop.
Example of how to use methods in R to have the print() function print out something special based on function output
#########################
# Print methods in R #
#########################
#Create my silly function
myfunc <- function(mu){
x <- rnorm(1, mean=mu, sd=3)
class(x) <- "myfunc"
return(x)
}
#Run my silly function
a <- myfunc(15)
#This tells print() function how to deal with things of class "myfunc"
print.myfunc <- function(x){
dig <- floor(x) %% 10
cat("\t\n",
sprintf("The number I drew: %s\n", x),
sprintf("The ones digit is: %s", dig))
}
#Now print automagically knows what to print!
print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment