Get startedGet started for free

Refactoring: functions

Copying and pasting once is OK, but three times usually suggests something is wrong.

The provided code calculates an approximate 95% confidence interval for the variables x and y.

This exercise is part of the course

Defensive R Programming

View Course

Exercise instructions

  • Create a function called ci(), taking a single argument called values with no default values.
  • Get the function to return the 95% confidence interval.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

n <- length(x); m <- mean(x); s <- sd(x)
c(m - 1.96 * s / sqrt(n), m + 1.96 * s / sqrt(n))

n <- length(y); m <- mean(y); s <- sd(y)
c(m - 1.96 * s/sqrt(n), m + 1.96 * s/sqrt(n))

# Define a function to prevent pasting the code above
ci <- function(values) {
  n <- length(values)
  m <- ___ 
  s <- ___ 
  c(m - ___, m + ___)
}
Edit and Run Code