Alan Zarychta

GEOG 5023: Quantitative Methods In Geography

Homework 1: Intro to R

Using Functions in R:

rain <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
rain
##  [1] 16 18 14 22 27 17 19 17 17 22 20 22
sum(rain)
## [1] 231
length(rain)  #returns the length of the list (vector)
## [1] 12
sum(rain)/length(rain)
## [1] 19.25
mean(rain)
## [1] 19.25
rain - mean(rain)
##  [1] -3.25 -1.25 -5.25  2.75  7.75 -2.25 -0.25 -2.25 -2.25  2.75  0.75
## [12]  2.75
rainDeviations <- rain - mean(rain)
rainDeviations
##  [1] -3.25 -1.25 -5.25  2.75  7.75 -2.25 -0.25 -2.25 -2.25  2.75  0.75
## [12]  2.75
rainDeviations^2
##  [1] 10.5625  1.5625 27.5625  7.5625 60.0625  5.0625  0.0625  5.0625
##  [9]  5.0625  7.5625  0.5625  7.5625
sqrt(rain)
##  [1] 4.000 4.243 3.742 4.690 5.196 4.123 4.359 4.123 4.123 4.690 4.472
## [12] 4.690

Calculate SD of Rainfall Data:

rain
##  [1] 16 18 14 22 27 17 19 17 17 22 20 22
rainDeviations
##  [1] -3.25 -1.25 -5.25  2.75  7.75 -2.25 -0.25 -2.25 -2.25  2.75  0.75
## [12]  2.75
rainDeviations.Squared <- rainDeviations^2
mean.rainDeviations.Squared <- mean(rainDeviations.Squared)
sd.rain <- sqrt(mean.rainDeviations.Squared)
sd.rain
## [1] 3.394

Writing Functions in R:

A function to calculate the mean of an object:

myMean <- function(someData) {
    return(sum(someData)/length(someData))
}
myMean(rain)
## [1] 19.25
mean(rain)
## [1] 19.25

A function to convert values in inches to values in centimeters:

in.to.cm <- function(someDataInInches) {
    return(someDataInInches/0.3937)
}
rain/0.3937
##  [1] 40.64 45.72 35.56 55.88 68.58 43.18 48.26 43.18 43.18 55.88 50.80
## [12] 55.88
in.to.cm(rain)
##  [1] 40.64 45.72 35.56 55.88 68.58 43.18 48.26 43.18 43.18 55.88 50.80
## [12] 55.88

Assignment:

A function to calculate the standard deviation of an object:

mySD <- function(someData) {
    return(sqrt(mean((someData - mean(someData))^2)))
}
mySD(rain)
## [1] 3.394