MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Defensive R Programming

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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 dan Jalankan Kode