Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

R Vector Operations


Share

Math on Vectors

In many programming languages, you need a loop to change every item in a list.

In R, math works on the whole vector at once. This is one of the things that makes R so good for working with data:

Example

prices <- c(10, 20, 30)

prices * 2
prices + 5
Try it Yourself »

Every item is multiplied by 2, and then 5 is added to every item.

If you use two vectors of the same length, R works item by item. The first items are added together, then the second items, and so on:

Example

a <- c(1, 2, 3)
b <- c(10, 20, 30)

a + b
Try it Yourself »

Functions on Vectors

Many functions work on all the items in a vector. For example sum(), mean() (the average), min() and max():

Example

scores <- c(85, 92, 78, 90)

sum(scores)
mean(scores)
max(scores)
Try it Yourself »

Compare Vectors

A comparison also works on every item. The result is a vector of TRUE and FALSE values:

Example

scores <- c(85, 42, 78, 30)

scores > 50
Try it Yourself »


Filter a Vector

Put a condition inside the brackets [] to get only the items where the condition is TRUE:

Example

scores <- c(85, 42, 78, 30)

scores[scores > 50]
Try it Yourself »

Only 85 and 78 are greater than 50, so only they are returned.

Use which() to get the positions of the items that match, and sum() to count them (R counts each TRUE as 1):

Example

scores <- c(85, 42, 78, 30)

which(scores > 50)
sum(scores > 50)
Try it Yourself »

The ifelse() Function

The ifelse() function checks a condition for every item, and returns one value if it is TRUE, and another value if it is FALSE:

Example

scores <- c(85, 42, 78, 30)

ifelse(scores > 50, "Pass", "Fail")
Try it Yourself »


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.