9.7 Two-dimensional structures manipulation

9.7.2 Manipulation

Same principle as vectors… but in 2 dimensions! Examples

  • Select rows of b if at least one element in column 2 is greater than 24 (i.e. select patients if they are older than 24):

  • Select patients (rows) based on 2 criteria: age of the patient (column 2) should be great than or equal to 25, and the patient should be vegetarian (column 3):

  • Select the columns of b if at least one element in the 3rd row is less than or equal to 4: More useful commands

  • Add a row or a column with rbind and cbind, respectively

Add a patient to our data frame d:

  • Process the sum of all rows or all columns with rowSums and colSums, respectively.
  • The apply function

Powerful tool to apply a command to all rows or all columns of a data frame or a matrix.
For example, instead of calculating the sum of each row, you might be interested in calculating the median ? But rowMedians doesn’t exist !

apply takes 3 arguments:

  • first argument X: 2-dimensional object
  • second argument MARGIN: apply by row or by column?
    • 1: by row
    • 2: by column
  • third argument FUN: function to apply to either rows or columns