Menu
Coddy logo textTech

Output With Variables

Part of the Fundamentals section of Coddy's R journey — lesson 28 of 78.

Now that you know how to use cat(), let's see how to include variables in your output. This is essential for creating dynamic messages that change based on your data.

With cat(), you can mix text and variables by separating them with commas:

name <- "Alice"
age <- 25

cat("Name:", name, "\n")
cat("Age:", age, "\n")

This outputs:

Name: Alice 
Age: 25

You can combine multiple variables and text in a single cat() call:

item <- "apples"
quantity <- 5

cat("You bought", quantity, item, "\n")

This outputs: You bought 5 apples

Remember that cat() automatically adds spaces between items. You can also include calculations directly:

price <- 10
cat("Total cost:", price * 2, "\n")

This outputs: Total cost: 20

challenge icon

Challenge

Easy

Create a message that displays information about a book using variables and cat().

You are provided with the following variables:

title <- "The R Guide"
pages <- 350
price <- 29.99

Use cat() to display the following output, including a calculation for the discounted price (20% off):

Book: The R Guide
Pages: 350
Original Price: 29.99
Sale Price: 23.992

Each piece of information should appear on its own line. Calculate the sale price directly within the cat() call by multiplying price by 0.8.

Cheat sheet

To include variables in your output with cat(), separate text and variables with commas:

name <- "Alice"
age <- 25

cat("Name:", name, "\n")
cat("Age:", age, "\n")

You can combine multiple variables and text in a single cat() call:

item <- "apples"
quantity <- 5

cat("You bought", quantity, item, "\n")

cat() automatically adds spaces between items. You can also include calculations directly:

price <- 10
cat("Total cost:", price * 2, "\n")

Try it yourself

# Book information variables
title <- "The R Guide"
pages <- 350
price <- 29.99

# TODO: Use cat() to display the book information
# Each piece of information should be on its own line
# Calculate the sale price (20% off) directly in the cat() call
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals