Skip to content

Instantly share code, notes, and snippets.

@geofferyzh
Created April 17, 2012 15:37
Show Gist options
  • Save geofferyzh/2406915 to your computer and use it in GitHub Desktop.
Save geofferyzh/2406915 to your computer and use it in GitHub Desktop.
RinAction - R Functions - User-Written Functions
#####################################################
# ---------- 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