Created
April 17, 2012 15:37
-
-
Save geofferyzh/2406915 to your computer and use it in GitHub Desktop.
RinAction - R Functions - User-Written Functions
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
##################################################### | |
# ---------- User Written Function -----------------# | |
# - objects in the function are local to the function | |
# - object returned can be any data type | |
##################################################### | |
mystats <- function(x, parametric=TRUE, print=FALSE) { | |
if (parametric) { | |
center <- mean(x); spread <- sd(x) | |
} else { | |
center <- median(x); spread <- mad(x) | |
} | |
if (print & parametric) { | |
cat("Mean=", center, "\n", "SD=", spread, "\n") | |
} else if (print & !parametric) { | |
cat("Median=", center, "\n", "MAD=", spread, "\n") | |
} | |
result <- list(center=center, spread=spread) | |
return(result) | |
} | |
# trying it out | |
set.seed(1234) | |
x <- rnorm(500) | |
y <- mystats(x) | |
y | |
y <- mystats(x, parametric=FALSE, print=TRUE) | |
y | |
# remove a self-written function from memory | |
rm('knn') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment