← Back to R Course | Chapter 3: Vectors | Lesson 6 of 7

Vector Functions

Vector functions are ready-made tools that look at a whole list at once, such as adding everything up or finding its length. They save you from doing it by hand.

In this page:

  1. Vector Functions
Syntax
r
length(vector_name)
sum(vector_name)
mean(vector_name)
max(vector_name)
sort(vector_name)

Vector Functions

R provides many built-in functions that operate on an entire vector at once, like sum(), length(), max(), min(), and sort().

These are typically implemented in optimized C code and run much faster than an equivalent manual loop. Learning these functions is key to writing concise, idiomatic R.

Note: Reach for a built-in vector function like sum() or sort() before writing a manual for-loop -- one almost always exists.

Example: Vector Functions

markup
v <- c(5, 3, 8, 1, 9)

cat("Sum:", sum(v), "\n")
cat("Max:", max(v), "\n")
cat("Min:", min(v), "\n")
print(sort(v))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling sum on a vector containing NA and getting NA, when na.rm = TRUE is needed.
  2. Expecting sort(v) to change v, when it returns a sorted copy.
  3. Using max(v1, v2) to compare element by element, when it returns one maximum; use pmax().
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.