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:
Syntax
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
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))
Login to try C/C++/Java/PHP code in the editor
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
- Calling
sumon a vector containingNAand gettingNA, whenna.rm = TRUEis needed. - Expecting
sort(v)to changev, when it returns a sorted copy. - Using
max(v1, v2)to compare element by element, when it returns one maximum; usepmax().
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: