53  53. function, matrix questions

53.1 Problem 1: Area of a Circle

Create a function named areaOfCircle.

  • It should take one argument called radius.
  • It should return the area of a circle.
  • Use R’s predefined constant pi.
areaOfCircle <- function(radius) {
  pi * radius^2
}

53.2 Problem 2: Upper-Right Quadrant

Create a function named upperRightQuadrant.

  • The argument data will be a matrix or data frame.
  • The number of rows and columns will be even.
  • Return the upper-right quadrant.
upperRightQuadrant <- function(data) {
  nr <- nrow(data)
  nc <- ncol(data)

  rows <- 1:(nr / 2)
  cols <- (nc / 2 + 1):nc

  data[rows, cols, drop = FALSE]
}

53.3 Problem 3: Input Validation

Modify upperRightQuadrant so that it stops with an error if the data does not have an even number of rows and columns.

upperRightQuadrant <- function(data) {
  nr <- nrow(data)
  nc <- ncol(data)

  if (nr %% 2 != 0 || nc %% 2 != 0) {
    stop("data must have an even number of rows and an even number of columns")
  }

  rows <- 1:(nr / 2)
  cols <- (nc / 2 + 1):nc

  data[rows, cols, drop = FALSE]
}

53.4 Problem 4: General Quadrant Function

Create a function named getQuadrant.

  • Argument data is a matrix or data frame with even dimensions.
  • Argument n indicates which quadrant to return:
    • 1 = upper left
    • 2 = upper right
    • 3 = lower right
    • 4 = lower left
  • If n is missing, return the upper-left quadrant.
  • Otherwise, stop with an error.
getQuadrant <- function(data, n = 1) {
  nr <- nrow(data)
  nc <- ncol(data)

  if (nr %% 2 != 0 || nc %% 2 != 0) {
    stop("data must have an even number of rows and an even number of columns")
  }

  if (!is.numeric(n) || length(n) != 1 || !(n %in% 1:4)) {
    stop("n must be a single number and must have the value 1,2,3 or 4")
  }

  r_mid <- nr / 2
  c_mid <- nc / 2

  if (n == 1) data[1:r_mid, 1:c_mid, drop = FALSE]
  else if (n == 2) data[1:r_mid, (c_mid + 1):nc, drop = FALSE]
  else if (n == 3) data[(r_mid + 1):nr, (c_mid + 1):nc, drop = FALSE]
  else data[(r_mid + 1):nr, 1:c_mid, drop = FALSE]
}

© 2025 Y. Rosenthal. All rights reserved.