When we printed our matrix, the rows have a next to them, and the columns have a. Note that R is actually trying to help us out here. In R, rows are on the left side of the comma, and columns are on the right (a third dimension would be after the second comma, and so on…). When indexing using an object with multiple dimensions, we use a, to separate them. We now have not only one, but two dimensions to choose from. However, indexing a matrix is slightly different from indexing in a vector. # 22 24 26 28 30 dim(mat) # grab dimensions of a matrix # 2 5 length(mat) # number of elements in a matrix # 10 mat <- matrix(1:10, nrow=2, ncol=5)Īll of the same operations that work on vectors also work on matrices. In this case, we are creating a matrix with 2 rows and 5 columns. One important note here: functions often have optional, “extra” arguments that are specified with name=value notation. Let’s create a matrix with the matrix() function. We will go more in-depth as to why later on.Ī matrix is a two-dimensional vector. Though this is actually valid code in R (indexing outside of a vector’s size is an error in most other languages), it comes at a performance cost. NA is R’s placeholder for “no data” (since 0 often shows up in real data). Notice that R “fills in the blanks” with NA values. It’s even possible to index outside the bounds of a vector. For instance, we could change the 3rd and 5th values to 76 with the following code: concat <- 76 We can use this technique to reassign certain values inside the vector. Putting another vector inside the brackets gives us multiple values, for instance. We can actually put anything inside the square brackets. In this case, length() is used to get the length of a vector, and since the lenght of the vector will be equal to the index of its last element, this is a nifty way of getting the last element of a vector. Notice that for the second example, we put a function inside the square brackets. To get other elements, we could do the following: concat # second element # 17 concat # last element # 2 This is different than 0-based languages like C, Python, or Java where the first element is at index 0. In R, array indexes start at 1 - the 1st element is at index 1. To get the first element of a vector, we could do the following. We do this by indexing (uses the brackets). Perhaps we only want a single element, or a set of specific elements. Often, we don’t want to get the entire vector.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |