Last active
March 31, 2016 02:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
######################### | |
# 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