Solution to the exercise

Based on an on-line search, you will quickly learn that the R function to use for creating a pie plot is pie(). In the documentation (run ?pie), you will see that the function’s first parameter is x and should refer to “a vector of non-negative numerical quantities”, and that “the values in x are displayed as the areas of pie slices”. That is, x should refer to the observed counts. We can store these counts in a vector named obs and run the pie function:

obs <- c(57, 28, 15)
pie(x = obs)

This pie chart already looks similar to the chart in the exercise, with three exceptions:

  1. The colors do not match,
  2. It shows numbers instead of informative labels,
  3. It has no title.

From the function documentation, it can be observed that the parameters that need to be used to adjust the colors, labels and title are `col, labels, and main, respectively. Parameter col requires a “a vector of colors to be used in filling or shading the slices”. In this case, the colors used are green, orange, and red (in that order). We can store these character values in a vector as well, and use it in the function as follows:

obs <- c(57, 28, 15)
cols <- c('Green', 'Orange', 'Red')
pie(x = obs, col = cols)

The labels can be added in a similar manner:

obs <- c(57, 28, 15)
cols <- c('Green', 'Orange', 'Red')
smokestat <- c('Never-smoker', 'Ex-Smoker', 'Current smoker')
pie(x = obs, col = cols, labels = smokestat)

Lastly, to include the title, we specify main:

obs <- c(57, 28, 15)
cols <- c('Green', 'Orange', 'Red')
smokestat <- c('Never-smoker', 'Ex-Smoker', 'Current smoker')
pie(x = obs, col = cols, labels = smokestat, main = 'smoking status')

Note that we do not necessarily need to store the counts, colors and labels in objects before running pie(). I.e. the same results will be obtained using the following command:

pie(x = c(57, 28, 15), col = c('Green', 'Orange', 'Red'), labels = c('Never-smoker', 'Ex-Smoker', 'Current smoker'), main = 'smoking status')