Course Content

R Introduction: Part II

Manipulating Columns

Let's continue to expand our data frames manipulation arsenal! :)

Next on the line - is adding/deleting columns. First, to add a new column, assign a vector of values to the column with a new name. You can do it by using either name in square brackets or the dollar `\$` sign. For example, let's add to the people data frame column with Job titles.

You could also add this column using `test[,'Job'] <- ...`. Also, note that the length of the vector of values you add must equal the number of rows in the data frame (i.e., you can not add a column with two values if there are ten rows in the data frame). To remove column(s) out of data frame use `subset()` function, with the first parameter being data frame, and `select = - ...`, where `...` is the name(s) of column(s) you want to drop. For example, we can drop `'gender'` column.

And lastly, if you want to change column names, use the same approach as for matrices - `colnames()` function. Remember, `colnames(data) <- new_names` is the syntax for this operation.

Given data frame `store` with the information on items and their prices in a small furniture store. Currently, it looks like this:

 items prices Sofa 340 Armchair 150 Dining table 115 Dining chair 45 Bookshelf 160

You need to transform this table into this:

 Item Price Sold Sofa 340 67 Armchair 150 81 Dining table 115 79 Dining chair 45 76 Bookshelf 160 42

1. Rename the columns names of `store` to `c('Item', 'Price')`.
2. Add new column `'Sold'` with the values of `c(67, 81, 79, 76, 42)`.