Indexing and Subsetting - Practical
Preface
Open Rstudio to do the practicals. Note that tasks with * are optional.
R packages
In this practical, a number of R packages are used. The packages used (with versions that were used to generate the solutions) are:
survival
(version: 3.5.7)
R version 4.3.2 (2023-10-31 ucrt)
Dataset
For this practical, we will use the heart and retinopathy data sets from the survival
package. More details about the data sets can be found in:
https://stat.ethz.ch/R-manual/R-devel/library/survival/html/heart.html
https://stat.ethz.ch/R-manual/R-devel/library/survival/html/retinopathy.html
Indexing and Subsetting
Sometimes we want to obtain a subset of the data sets before investigating the descriptive statistics and performing the statistical analysis.
Indexing
Using the heart data set:
- Select the first row.
- Select the first column.
- Select the column
surgery
.
Create a matrix that takes the values 1:4 and has 2 rows and 2 columns. You can name this object mat
. Select the second row of all columns.
Create an array that consists of 2 matrices. Matrix 1 will consist of the values 1:4 and matrix 2 will consist of the values 5:8. Both matrices will have 2 columns and 2 rows. Give the name ar1
to the this array. Select the 2nd row of all columns from each matrix.
Subsetting
Using the retinopathy data set:
- Select the
futime
for alladult
patients.
- Select all the variables for patients that received treatment.
Using the retinopathy data set:
- Select the
age
for patients that havefutime
more than 20.
- Select the
age
for patients that havefutime
more than 20 and are adults.
- Select patients that have no missing values in
age
.
Using the retinopathy data set:
- Select only the rows of the left eye.
- Select only the rows of adult patients.