A very simple table

Combining format() and paste() is one way to display very simple tables. Remember, since format() looks at all the values in a vector before formatting, it uses a consistent format and will, by default, align on the decimal point. This is usually the behavior you want for a column of numbers in table.

format() can also take character vectors as input. In this case, you can use the justify argument, specific to character input, to justify the text to the left, right, or center.

You are going to put together the following table:

          Year 0   $       72
          Year 1   $    1,030
          Year 2   $   10,292
Project Lifetime   $1,189,192

You'll start by formatting the columns to prepare to put them in a table, then you'll use paste() to put together each row. Then, you can use writeLines() to display each row on a new line.

This exercise is part of the course

String Manipulation with stringr in R

View Course

Exercise instructions

The income vector is loaded in your workspace.

  • Create pretty_income by using format() with digits = 2 and big.mark = ",".
  • Create dollar_income by pasting $ to pretty_income (don't forget to set the sep argument).
  • Create formatted_names by using format() on income_names with justify = "right".
  • Create rows by pasting together formatted_names and dollar_income. Use three spaces as a separator to give some room between your columns. Be sure to surround your separator in ".
  • Call writeLines() on rows to see your table.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define the names vector
income_names <- c("Year 0", "Year 1", "Year 2", "Project Lifetime")

# Create pretty_income
pretty_income <- ___

# Create dollar_income
dollar_income <- ___

# Create formatted_names
formatted_names <- ___

# Create rows
___

# Write rows
___