In the previous exercise, we used numeric columns to create other numeric columns. The procedure is the same for character vectors.
For example, we can extract the quarter and store this information in a new column called
quarter. We know that the
quarter_prices data frame has a column named
period that stores both the quarter and the year, in the following format: "Q# YYYY".
Thus, we can extract
"Q#" for each quarter by using the
substring() function, and store that extracted value in a new column
quarter like this:
quarter_prices$quarter <- substring(quarter_prices$period, 1,2)
The first argument is the character column
period. The next two arguments specify the start and end (inclusive) indexes of the substring we wish to extract. Remember that indexing begins with 1 in R. Here's the resulting data frame:
Note that there is no error when the end index exceeds the length of the string.