0
0
R-programmingHow-ToBeginner · 3 min read

How to Use summary() in R: Syntax and Examples

In R, use the summary() function to get a quick overview of an object’s main statistics like minimum, maximum, mean, and quartiles. Just pass your data object (like a vector, data frame, or factor) inside summary() to see its summary.
📐

Syntax

The basic syntax of summary() is simple:

  • summary(object): Returns summary statistics of the object.
  • object can be a vector, factor, data frame, or other R objects.

The output depends on the object type, showing relevant statistics or counts.

r
summary(object)
💻

Example

This example shows how to use summary() on a numeric vector and a data frame to get descriptive statistics.

r
numbers <- c(10, 20, 30, 40, 50)
data <- data.frame(
  age = c(25, 30, 35, 40, 45),
  gender = factor(c("male", "female", "female", "male", "female"))
)

summary(numbers)
summary(data)
Output
Min. 1st Qu. Median Mean 3rd Qu. Max. 10.00 20.00 30.00 30.00 40.00 50.00 age gender Min. :25.0 female:3 1st Qu.:30.0 male :2 Median :35.0 Mean :35.0 3rd Qu.:40.0 Max. :45.0
⚠️

Common Pitfalls

Some common mistakes when using summary() include:

  • Passing unsupported object types that don’t have a summary method.
  • Expecting detailed statistics for all objects; some show only counts or basic info.
  • Confusing summary() with functions like str() or describe() which provide different details.

Always check the object type before using summary() to understand the output.

r
wrong_object <- function(x) x

# This will cause an error because summary() has no method for functions
# summary(wrong_object)

# Correct: use summary on supported objects like vectors or data frames
summary(c(1,2,3))
Output
Min. 1st Qu. Median Mean 3rd Qu. Max. 1.00 1.50 2.00 2.00 2.50 3.00
📊

Quick Reference

Tips for using summary() effectively:

  • Use on numeric vectors for min, max, mean, quartiles.
  • Use on factors to get counts of each level.
  • Use on data frames to get summaries of each column.
  • Works on many built-in R objects with tailored outputs.

Key Takeaways

Use summary(object) to get quick statistics or counts depending on the object type.
summary() works well on vectors, factors, and data frames for descriptive insights.
Check the object type first to understand what summary() will return.
Avoid using summary() on unsupported objects like functions to prevent errors.
summary() is a fast way to explore your data’s main features in R.