CSC121 - R Console Friday February 9th --------------------------- > # Recall our list from last time > n <- 121 > s <- "csc" > v <- c(432, 2, 98) > t <- TRUE > L <- list(n, s, v, t) > L [[1]] [1] 121 [[2]] [1] "csc" [[3]] [1] 432 2 98 [[4]] [1] TRUE > > # Adding elements to a list > # We can add elements to a list using the 'append' function > # 'append' means to add to the end of the list > append(L, "appended") [[1]] [1] 121 [[2]] [1] "csc" [[3]] [1] 432 2 98 [[4]] [1] TRUE [[5]] [1] "appended" > Notice that this only returns a copy of L with the appended element Error: unexpected symbol in " Notice that" > # It does NOT change L > L [[1]] [1] 121 [[2]] [1] "csc" [[3]] [1] 432 2 98 [[4]] [1] TRUE > # We must use an assignment statement > L <- append(L, "appended") > L [[1]] [1] 121 [[2]] [1] "csc" [[3]] [1] 432 2 98 [[4]] [1] TRUE [[5]] [1] "appended" > # We can also add elements at different points in the list by adding an extra argument to append() > L3 <- list(1, "2") > append(L3, "appended", 1) [[1]] [1] 1 [[2]] [1] "appended" [[3]] [1] "2" > # In this case, the last argument in appended is 1, which indicates *after* which index we want to append the element (in this case, after index 1) > # It is NOT at which index the element will be when added > # If we wanted it to be added at index 1 (beginning of list), we would give an argument of 0 > append(L3, "appended", 0) [[1]] [1] "appended" [[2]] [1] 1 [[3]] [1] "2" > length(L) [1] 5 > length(L3) [1] 2 > # You can find the length of a list with length(), just like vectors > L3 <- append(L3, "appended", 0) > L3 [[1]] [1] "appended" [[2]] [1] 1 [[3]] [1] "2" > length(L3) [1] 3 > > # Changing elements at an index > # Just like vectors, we can change a list in place > L3[2] <- 45 > L3 [[1]] [1] "appended" [[2]] [1] 45 [[3]] [1] "2" > L3[[2]] <- 77 > L3 [[1]] [1] "appended" [[2]] [1] 77 [[3]] [1] "2" > # Remove element > # One way is just to index without that element present > L3 [[1]] [1] "appended" [[2]] [1] 77 [[3]] [1] "2" > L3[2:length(L3)] [[1]] [1] 77 [[2]] [1] "2" > # To remove an element at *any* index, you can assign it the value NULL > L3 [[1]] [1] "appended" [[2]] [1] 77 [[3]] [1] "2" > L3[2] <- NULL > L3 [[1]] [1] "appended" [[2]] [1] "2" > # Notice that the element at index 3 originally was pushed up to index 2 after the removal > L3[-2] [[1]] [1] "appended" > # Negative indexes also work, but you need to assign the resulting list. Assigning the element to NULL is the way to change the list in place > L3 [[1]] [1] "appended" [[2]] [1] "2" > L3[2] <- NULL > L3 [[1]] [1] "appended" >