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: 25You 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
EasyCreate 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.99Use 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.992Each 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() callThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values