Cat for Output
Part of the Fundamentals section of Coddy's R journey — lesson 27 of 78.
The cat() function gives you cleaner output compared to print(). While print() adds quotes around strings and shows index numbers, cat() displays text exactly as you want it to appear.
cat("Hello, World!")This outputs Hello, World! without any quotes or index markers.
The name "cat" comes from "concatenate," meaning it can join multiple items together in a single output:
cat("Hello", "World") # Output: Hello WorldNotice that cat() automatically adds a space between items. One important difference from print() is that cat() doesn't automatically move to a new line. To create a line break, use \n:
cat("Line one\n")
cat("Line two")This outputs:
Line one
Line twoThe \n is called a newline character. You'll use cat() frequently when you want precise control over how your output looks.
Challenge
EasyUse the cat() function to display a formatted message across multiple lines.
You are provided with the following variables:
product <- "Laptop"
price <- 999
in_stock <- TRUEUse cat() to display the following output exactly as shown, with each piece of information on its own line:
Product: Laptop
Price: 999
Available: TRUERemember to use \n to create line breaks and that cat() automatically adds spaces between items.
Cheat sheet
The cat() function displays text without quotes or index markers, providing cleaner output than print():
cat("Hello, World!")The function can concatenate multiple items, automatically adding spaces between them:
cat("Hello", "World") # Output: Hello WorldTo create line breaks, use the newline character \n:
cat("Line one\n")
cat("Line two")
# Output:
# Line one
# Line twoTry it yourself
# Variables are already defined for you
product <- "Laptop"
price <- 999
in_stock <- TRUE
# TODO: Use cat() to display the formatted message with each piece of information on its own line
# Remember to use \n for line breaksThis 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