Home > Teaching > Tutorials > R Tutorial Index
some useful functions
To use a function below, copy and paste the corresponding line in black (starts with 'source') into R. This will load the function into R and will make it available for use. Follow the directions that accompany a function for how to use it.
source("http://www.stat.ucla.edu/~david/teac/r/func/add_normal.R")
# add.normal is a function to add a normal curve to an
# existing histogram made with 'hist'. the function is
# explicitly written out below in the R language:
add.normal <- function(data, color="blue"){
R <- range(data)
M <- mean(data)
SD <- sd(data)
#==> setting up an vector over the domain <==#
#==> change the 200 to a larger number for more curve detail <==#
x <- seq(R[1]-SD, R[2]+SD, length.out=200)
#==> finding the normal density over x <==#
y <- dnorm(x, M, SD)
#==> plotting the points <==#
points(x, y, type="l", col=color)
}
# function rule: the input for the function must be a numerical data vector
# below is an example of how to use this function:
# download and attach the data
bumpus <- read.delim("http://www.stat.ucla.edu/~david/Bumpus.txt", header=T)
attach(bumpus)
# the next two lines of code create a histogram and then plot the normal curve
# to one of the numerical columns of bumpus:
hist(Length_mm[Survival], freq=F) # it is crucial to have 'freq=F' in hist
add.normal(Length_mm[Survival])