3.7 Summary of R Objects
Through the last chapter and this one, we have covered all major types of R objects including vectors, matrices, arrays, data frames (tibbles), and lists. In this section, we would like to summarize what we have covered and highlight the main differences of the different types of objects in terms of their dimensions and the data types they can contain.
| Type | Section | Dim | Data Type |
|---|---|---|---|
| Vector | 2 | 1 | Single |
| Matrix | 3.1 | 2 | Single |
| Array | 3.2 | >=3 | Single |
| Data Frame/Tibble | 3.3 - 3.4 | 2 | Multiple |
| List | 3.5 | 1 | Multiple |
3.7.1 Exercises
This exercise will guide you through various R operations using a dataset of animals in a zoo. You will practice creating and manipulating vectors, matrices, and data frames, as well as performing basic calculations and filtering.
Suppose there are 3 lions, 5 tigers, 7 birds, and 2 monkeys in the zoo.
- Creating Vectors
- Create a numeric vector named
countthat stores the number of each animal: lions, tigers, birds, and monkeys. - Create a character vector named
animalthat stores the names of these animals in the same order.
- Combining Vectors
- Combine the
countandanimalvectors into a new vectorzoo_1 <- c(count, animal). - What is the data type of
zoo_1? Why does it has such a data type? What are the implications of this for numerical calculations?
- Creating a Matrix
- Combine the
countandanimalvectors into a matrixzoo_2 <- cbind(count, animal). - What is the data type of
zoo_2? Explain why this occurs and how R handles the different data types within a matrix.
- Creating a Data Frame
- Create a data frame named
zoo_dfusing thecountandanimalvectors. Ensure that the data frame has appropriate column names. - Display the structure of the data frame using the
str()function. What are the data types of each column?
- Updating the Data Frame
- Two birds have escaped from the zoo. Update the
zoo_dfdata frame to decrease the bird count by 2. - Verify the update by displaying the
zoo_dfdata frame.
- Filtering the Data Frame
- Extract and display only the rows of
zoo_dfthat correspond to lions and tigers using subsetting.
- Adding New Data
- The zoo has acquired 6 pandas. Add a new row to
zoo_dffor the pandas with the appropriate count and animal name. - Display the updated data frame.
- Calculating the Total Number of Animals
- Calculate the total number of animals in the zoo without using the
+operator.
- Adding a Placeholder Row
- The zoo manager plans to add parrots to the zoo, but he doesn’t know the exact number yet. Add a row for “parrots” with a placeholder value of
NAfor the count. - Display the updated data frame to confirm the change.
- Calculating the Median Count
- The zoo manager decides that the number of parrots should be set to the median of the existing animal counts. Calculate the median count, excluding any
NAvalues. - Update the count for parrots in the data frame to this median value.
- Display the final data frame.