print() & str()
in R Programming
Learn to display output and inspect object structure using R's two most essential debugging and exploration functions.
Why Inspect Objects?
Every R variable holds data, but you can't always see what's inside just by looking at your code. Inspecting objects lets you verify values, understand data types, and catch bugs before they cascade into errors.
What is print()?
print() displays the value of an R object in the console. It's how R shows you data: numbers, text, vectors, data frames, and more.
What is str()?
str() stands for "structure." It reveals the internal blueprint of any R object: data type, dimensions, and a compact preview of the contents.
The R Object Model
print() reveals the value side. str() reveals the structural side. Together, they give you the complete picture.
The print() Function
The str() Function
print() vs str(): The Key Difference
How to Apply Both Functions
Example 1: Inspecting a Vector
Example 2: Inspecting a List
Example 3: Inspecting a Data Frame
Auto-Printing vs Explicit print()
When to Use Which Function
Common Mistakes
Summary Comparison
| print() | str() | |
|---|---|---|
| Purpose | Display values | Display structure |
| Shows types? | No | Yes |
| Shows dimensions? | Partially | Yes |
| Needed in loops? | Yes | Rarely |
| Best for | Showing results | Exploring data |
| Output style | Formatted, readable | Compact, technical |
Question 1 of 5
What does the str() function in R stand for?
Question 2 of 5
What happens when you type x (without print()) inside a for-loop in R?
Question 3 of 5
Consider the following R code and its output:
y <- c("apple", "banana", "cherry")
str(y)
chr [1:3] "apple" "banana" "cherry"
In the str() output above, what does chr [1:3] tell you?
Question 4 of 5
You receive a data frame but don't know what columns it has or their types. Which function should you call first?
Question 5 of 5
A student writes this function and is confused that no output appears when they call it:
show_squares <- function(n) {
for (i in 1:n) {
\(i^2\)
}
}
show_squares(5)
How should the student fix the function so it displays each squared value?