course content

Course Content

R Introduction: Part II

Manipulating RowsManipulating Rows

Now let's learn how to add/delete rows. Let's consider two methods. The first is more applicable for adding a single row.

The method is to assign a new row to the last plus one index of an existing data frame (to get the number of rows, use the nrow() function). Remember that you can not store data of different types using vectors. So, you need to assign either a data frame or a list with new values. Do not worry if you do not know lists. In simple words, this is like a vector that allows us to store data of different types. Let's represent that. The initial data frame is shown below.

Note

By default, when changing a data frame, any new string values in a list are automatically converted to factors. To prevent this automatic conversion, the parameter stringsAsFactors = FALSE should be specified during the creation of the data frame. This approach should be applied whenever you are modifying rows in the data frame.

You could do this by using a new data frame and the merge function. This method requires the same column names and setting of necessary parameters (all = T).

As you can see, the outputs are identical. To remove rows out of the data frame, use square quotes and put a minus sign to the left of the row index. For example, test[-1,] will remove the first row (the same as for matrices)

Task

Let's continue working with the store data frame.

  1. Remove the 'Dining chair' row (index 4) out of the store data frame. Reassign the result to the store variable.
  2. Add a new row to the data frame store using the list approach with the data below.
ItemPriceSold
Kitchen Cabinet7067

Output modified data frame.

Everything was clear?

Section 2. Chapter 6
toggle bottom row