ModifyingModifying

Great! So far, you know how to create a vector, assign names to values, and extract elements from it. The next thing we will consider is modifying: adding and deleting existing items from a vector.

There are at least two ways to add a new value to an existing vector. Assume we have a vector named vec and want to add new_value to it. The name we want to assign to this value is 'new_name'. Both ways are displayed on the schema below.

For example, let me show you how both ways will work. Let's use the same grades example and add a new grade 60 for the 'Philosophy' subject. The first way is using vectors:

Now let's perform the second method - assigning names with values simultaneously.

So, if your vector has no names, then the first method is better. But if the vector has names - then it's better to use the second method. Using the second method, you can add new values and reassign them. For example, if you write grades['Math'] <- 100 - then the original value of 80 will be rewritten with 100. Also, you can refer to a specific index. The same trick can be done by writing grades[1] <- 100.

Task

  1. Add a new item named 'Desk' with the value of price 135 to the end of the prices vector using the second method (assigning name simultaneously to adding value).
  2. Change price of item 'Bookshelf' to 180. Feel free to use either index or name.
  3. Output modified vector prices.

Everything was clear?

Section 2. Chapter 9
toggle bottom row