This week we are introducing R functions and how to write our own functions.

Questions to answer:

Q1. Write a function grade() to determine an overall grade from a vector of student homework assignment scores dropping the lowest single score. If a student misses a homework (i.e. has an NA value) this can be used as a score to be potentially dropped. Your final function should be adquately explained with code comments and be able to work on an example class gradebook such as this one in CSV format: “https://tinyurl.com/gradeinput” [3pts]

plot(1:10)

# Example input vectors to start with
student1 <- c(100, 100, 100, 100, 100, 100, 100, 90)
student2 <- c(100, NA, 90, 90, 90, 90, 97, 80)
student3 <- c(90, NA, NA, NA, NA, NA, NA, NA)

Follow the guidelines from class

# Straight forward mean()
student1 <- c(100, 100, 100, 100, 100, 100, 100, 90)

mean(student1)
## [1] 98.75

But… We need to drop the lowest score. First we need to identify the lowest score.

#Which element of the vector is the lowest?
which.min(student1)
## [1] 8

What I want is to now drop (i.e exclude) this lowest score from my mean() calculation.

# This will return everything but the eighth element of the vector
student1[-8]
## [1] 100 100 100 100 100 100 100

Now we can use the answer from which.min() to return all other elements of the vector.

# This is our first working snippet
mean(student1[-which.min(student1)])
## [1] 100

What about the other example students? Will this work for them?

We could try using na.rm=TRUE argument for mean but this is pants! Not a good approach i.e unfair.

student2 <- c(100, NA, 90, 90, 90, 90, 97, 80)
mean(student2, na.rm=TRUE)
## [1] 91
student3 <- c(90, NA, NA, NA, NA, NA, NA, NA)
mean(student3, na.rm=TRUE)
## [1] 90

Another approach is to mask (i.e replace) all NA values with zero.

First we need to find the NA elements of the vector. How do we find the NA elements?

x <- student2

is.na(x)
## [1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
which(is.na(x))
## [1] 2

Now we have identified the NA elements we want to “mask” then. Replace them with zero?

# This does not quite get us there
mean(x[-which(is.na(x))])
## [1] 91

Instead we will make the NA elements zero.

# Cool, this is useful!
x[is.na(x)] <- 0
mean(x)
## [1] 79.625

Recall we should drop the lowest score now…

x[is.na(x)] <- 0
mean(x[-which.min(x)])
## [1] 91

Now we are essentially there.

student3 <- c(90, NA, NA, NA, NA, NA, NA, NA)
x <- student3
x[is.na(x)] <- 0
mean(x[-which.min(x)])
## [1] 12.85714

##Now we make our function

Take the snippet and turn into function Every function has 3 parts