11 Solutions || Data Types
11.1 Vectors
Make a vector with the numbers 1 through 26. Multiply the vector by 2, and give the resulting vector names A through Z (hint: there is a built in vector called LETTERS).
11.2 Matrices
Make a matrix with the numbers 1:50, with 5 columns and 10 rows. Did the matrix function fill your matrix by column, or by row, as its default behavior? Once you have figured it out, try to change the default. (hint: read the documentation for matrix
)
# By default the matrix is filled by columns, we can change this behavior using byrow=TRUE
m<-matrix(1:50,ncol = 5,nrow = 10,byrow = T)
Bonus: Which of the following commands was used to generate the matrix below?
matrix(c(4, 1, 9, 5, 10, 7), nrow = 3)
matrix(c(4, 9, 10, 1, 5, 7), ncol = 2, byrow = TRUE)
matrix(c(4, 9, 10, 1, 5, 7), nrow = 2)
matrix(c(4, 1, 9, 5, 10, 7), ncol = 2, byrow = TRUE)
## [,1] [,2]
## [1,] 4 1
## [2,] 9 5
## [3,] 10 7
11.3 Lists
Create a list of length two containing a character vector for each of the data sections: (1) Data types and (2) Data structures. Populate each character vector with the names of the data types and data structures, respectively.
11.4 Data frames
There are several subtly different ways to call variables, observations and elements from data frames. Try them all and discuss with your team what they return. (Hint, use the function typeof()
)
iris[1]
iris[[1]]
iris$Species
iris["Species"]
iris[1,1]
iris[,1]
iris[1,]
# The single brace [1] returns the first slice of the list, as another list. In this case it is the first column of the data frame.
iris[1]
# The double brace [[1]] returns the contents of the list item. In this case it is the contents of the first column, a vector of type factor.
iris[[1]]
# This example uses the $ character to address items by name. Species is a vector of type factor.
iris$Species
# A single brace ["Species"] instead of the index number with the column name will also return a list like in the first example
iris["Species"]
# First element of first row and first column. The returned element is an integer
iris[1,1]
# First column. Returns a vector
iris[,1]
# First row. Returns a list with all the values in the first row.
iris[1,]