# Use basic operators

May 8, 2020
By

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. R is not only good for analysing and visualizing data, but also for solving maths problems or comparing data with each other. Plus you can use it just like a pocket calculator.

• Use R as a pocket calculator
• Use arithmetic operators on vectors
• Use relational operators on vectors
• Use logical operators on vectors
```___ + ___
___ - ___
___ / ___
___ * ___
___ ^ ___

___ == ___
___ != ___
___ < ___
___ > ___
___ <= ___
___ >= ___

___ & ___
___ | ___

___ %in% ___```

## Using R as a pocket calculator

```___ + ___
___ - ___
___ / ___
___ * ___```

R is a programming language mainly developed for statistics and data analysis. Within R you can use mathematical operators just like you would use on a calculator. For example, you can add `+` and subtract `-` numbers from each other:

`5 + 5`
` 10`
`7 - 3.5`
` 3.5`

Similarly, you can multiply `*` or divide `/` numbers:

`5 * 7`
` 35`
`8 / 4`
` 2`

You can take the power of a number by using the `^` sign:

`2 ^ 3`
` 8`

According to the rules of mathematics, you can use round brackets to specify the order of evaluation in more complex tasks:

`5 * (2 + 4 / 2)`
` 20`

## Exercise: Use basic arithmetic

To calculate the mean of the numbers `2`, `3`, `7` and `8`:

1. Add all the numbers together using `+`.
2. Divide the result by the number of elements.
3. Make sure that the result of the addition is calculated first by using braces `()`.

Start Exercise

## Applying arithmetic operators on vectors

```___ + ___
___ - ___
___ / ___
___ * ___```

Operations, such as addition, subtraction, multiplication and division are called arithmetic operations. They can not only operate with single values but also with vectors. If you use arithmetic operations on vectors, the operation is done on each individual number from the first vector and the individual number at the same position from the second vector.

In the following example we create two numeric vectors and assign them to the variables `a` and `b`. We then add them together:

```a <- c(1, 3, 6, 9, 12, 15)
b <- c(2, 4, 6, 8, 10, 12)
a + b```
`  3  7 12 17 22 27`

As the output shows, the first elements of the two vectors were added together and resulted in `1 + 2 = 3`. The second elements added up to `3 + 4 = 7`, the third elements to `6 + 6 = 12` and so on.

We can apply any other arithmetic operation in a similar way:

```a <- c(22, 10, 7, 3, 14, 4)
b <- c(4, 5, 2, 6, 14, 8)
a / b```
` 5.5 2.0 3.5 0.5 1.0 0.5`

Using the same principle, the first element of the result is `22 / 4 = 5.5`, the second is `10 / 5 = 2` and so on.

## Quiz: Vector Multiplication

```odd <- c(1, 3, 5)
even <- c(2, 4, 6)
odd * even```

Inspect the code chunk above. What is the result of the multiplication?

• `108`
• `54`
• `15`, `48`
• `2`, `12`, `30`
• `18`, `36`, `54`

Start Quiz

## Exercise: Multiply numeric vectors

Multiply the numeric vectors `ascending` and `descending`:

1. Create a vector with the numbers `1`, `2`, `3` and `4` and assign it to the variable `ascending`.
2. Create a vector with the numbers `4`, `3`, `2` and `1` and assign it to the variable `descending`.
3. Multiply (`*`) the variable `ascending` with the variable `descending`.

Start Exercise

## Using relational operators

```___ == ___
___ != ___
___ < ___
___ > ___
___ <= ___
___ >= ___```

Relational operators are used to compare two values. The output of these operations is always a logical value `TRUE` or `FALSE`. We distinguish six different types relational operators, as we’ll see below.

The equal `==` and not equal `!=` operators check whether two values are the same (or not):

`2 == 1 + 1`
` TRUE`
`2 != 3`
` TRUE`

The less than `<` and greater than `>` operators check, whether a value is less or greater than another one:

`2 > 4`
` FALSE`
`2 < 4`
` TRUE`

The less than or equal to `<=` and the greater than or equal to `>=` operators combine the check for equality with either the less or the greater than comparison:

`2 >= 2`
` TRUE`
`2 <= 3`
` TRUE`

All of these operators can be used on vectors with one or more elements as well. In that case, each element of one vector is compared with the element at the same position in the other vector, just as with the mathematical operators:

```vector1 <- c(3, 5, 2, 7, 4, 2)
vector2 <- c(2, 6, 3, 3, 4, 1)
vector1 > vector2```
`  TRUE FALSE FALSE  TRUE FALSE  TRUE`

Therefore, the output of this example is based on the comparisons `3 > 2`, `5 > 6`, `2 > 3` and so on.

## Exercise: Compare numeric values

Use the appropriate relational operator and check whether 3 is greater than or equal to 2

Start Exercise

## Exercise: Compare temperatures

In the following exercise, we make use of the weather data gathered by the city of Innsbruck over the last decades. You are given two variables, `avgtemp_1997_2006` and `avgtemp_2007_2016`, each containing the monthly average temperatures in Innsbruck for the years 1997 to 2006 and 2007 to 2016.

Use an appropriate relational operator and check in which months there was an increase in the average temperature.

Start Exercise

## Using logical operators

```___ & ___
___ | ___```

The AND operator `&` is a used for checking whether multiple statements are `TRUE` at the same time. Using a simple example, we could check whether 3 is greater than 1 and at the same time if 4 is smaller than 2:

`3 > 1 & 4 < 2`
` FALSE`

3 is in fact greater than 1, but 4 is not smaller than 2. Since one of the statements is `FALSE`, the output of this joined evaluation is also `FALSE`.

The OR operator `|` checks only, whether any of the statements is `TRUE`.

`3 > 1 | 4 < 2`
` TRUE`

In an OR statement, not all elements have to be `TRUE`. Since 3 is greater than 1, the output of this evaluation is `TRUE` as well.

The `!` operator is used for the negation of logical values, which means it turns `TRUE` values to `FALSE` and `FALSE` values to `TRUE`. If we have a statement resulting in a logical `TRUE` or `FALSE` value, we can negate the result by applying the `!` operator on it. In the following example we check whether 3 is greater than 2 and then negate the result of this comparison:

`!3 > 2`
` FALSE`

Logical operators, just like arithmetic and relational operators, can be used on longer vectors as well. In the following example we use three different vectors `a`, `b` and `c` and try to evaluate multiple relations in combination.

```a <- c(1, 21, 3, 4)
b <- c(4, 2, 5, 3)
c <- c(3, 23, 5, 3)

a>b & b
 FALSE  TRUE FALSE FALSE
First, both relational comparisons `a>b` and `b are evaluated and result in two logical vectors. Therefore, we essentially compare the following two vectors:````
c(FALSE, TRUE, FALSE, TRUE) & c(FALSE, TRUE, FALSE, FALSE)
 FALSE  TRUE FALSE FALSE
The & operator checks whether both values at the same position in the vectors are TRUE. If any value of the pairs is FALSE, the combination is FALSE as well.
The | operator checks whether any of the values at the same position in the vectors is TRUE.
c(FALSE, TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE, FALSE)
 FALSE  TRUE FALSE  TRUE
Exercise: Use the & operator
You are given three variables alpha, beta and gamma. Use an appropriate logical operator and check whether alpha is greater than beta and at the same time gamma is smaller than beta.
Start Exercise
Exercise: Use the | operator
You are given three variables alpha, beta and gamma. Each contains a numeric vector of two elements. Use the appropriate logical operator and check whether alpha is greater than beta OR gamma is less than beta. (Hint: use the logical OR operator |)
Start Exercise
Using the %in% operator
___ %in% ___
One additional, often used special operator is the %in% operator. It checks whether or not the contents of one vector are present in another one as well.
In the following example we use the variable EU containing the abbreviation of all countries in the European Union. Then, we check whether or not the character "AU" is present in the EU variable.
EU <- c("AU","BE","BG","CY","CZ","DE","DK","EE","ES","FI","FR","GR","HR","HU",
"IE","IT","LT","LU","LV","MT","NL","PO","PT","RO","SE","SI","SK")
"AU" %in% EU
 TRUE
The following example extends the search and compares multiple elements with the contents of the EU variable. It outputs a logical vector as a result containing a logical value for each element:
c("AU","HU","UK") %in% EU
  TRUE  TRUE FALSE
As the output shows, the first two character elements "AU" and "HU" are present in the variable EU, however the third element "UK" is not.
Exercise: Use the %in% operator
You are standing in the supermarket and need to determine which you can check-off your shopping_list:

Use the %in% operator and determine which shopping_list items you can check-off your list based on the items in your basket.
Print the output of the resulting vector to the console.

Start Exercise
Use basic operators is an excerpt from the course Introduction to R, which is available for free on quantargo.com
VIEW FULL COURSE

var vglnk = { key: '949efb41171ac6ec1bf7f206d57e90b8' };

(function(d, t) {
var s = d.createElement(t); s.type = 'text/javascript'; s.async = true;
var r = d.getElementsByTagName(t); r.parentNode.insertBefore(s, r);
}(document, 'script'));

Related
ShareTweet

``` ```
``` Comments are closed. ```
``` Search R-bloggers Most visited articles of the week Free Springer Books during COVID19 5 Ways to Subset a Data Frame in R How to write the first for loop in R R – Sorting a data frame by the contents of a column Date Formats in R In-depth introduction to machine learning in 15 hours of expert videos Installing R packages Powerful Package for Machine Learning, Hyperparameter Tuning (Grid & Random Search), Shiny App Why R? Webinar - TUESDAY - Uplift modeling for marketing campaigns Sponsors // https://support.cloudflare.com/hc/en-us/articles/200169436-How-can-I-have-Rocket-Loader-ignore-my-script-s-in-Automatic-Mode- // this must be placed higher. Otherwise it doesn't work. // data-cfasync="false" is for making sure cloudflares' rocketcache doesn't interfeare with this // in this case it only works because it was used at the original script in the text widget function createCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); } async function readTextFile(file) { // Helps people browse between pages without the need to keep downloading the same // ads txt page everytime. This way, it allows them to use their browser's cache. var random_number = readCookie("ad_random_number_cookie"); if(random_number == null) { var random_number = Math.floor(Math.random()*100*(new Date().getTime()/10000000000)); createCookie("ad_random_number_cookie",random_number,1) } file += '?t='+random_number; var rawFile = new XMLHttpRequest(); rawFile.onreadystatechange = function () { if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status == 0) { // var allText = rawFile.responseText; // document.write(allText); document.write(rawFile.responseText); } } } rawFile.open("GET", file, false); rawFile.send(null); } // readTextFile('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt'); readTextFile("https://www.r-bloggers.com/wp-content/uploads/text-widget_anti-cache.txt"); Jobs for R usersData Analytics Auditor, Future of Audit LeadData Analytics Auditor, Future of Audit Lead @ London or NewcastleSenior Scientist, Translational Informatics @ Vancouver, BC, CanadaSenior Principal Data Scientist @ Mountain View, California, United StatesTechnical Research Analyst – New York, U.S.Movement Building AnalystInnovation Fellow python-bloggers.com (python/data-science news)Determine optimal sample sizes for business value in A/B testing, by Chris SaidMaking Pictures 3D using Context-aware Layered Depth InpaintingAdaOptAutomatically create perfect .gitignore file for your projectHow to Write a Git Commit Message, in 7 StepsPredictive Power Score: Finding predictive patterns in your datasetDocumentation+Pypi for the `teller`, a model-agnostic tool for Machine Learning explainability Full list of contributing R-bloggers ```
``` R-bloggers was founded by Tal Galili, with gratitude to the R community. Is powered by WordPress using a bavotasan.com design. Copyright © 2020 R-bloggers. All Rights Reserved. Terms and Conditions for this website var snp_f = []; var snp_hostname = new RegExp(location.host); var snp_http = new RegExp("^(http|https)://", "i"); var snp_cookie_prefix = ''; var snp_separate_cookies = false; var snp_ajax_url = 'https://www.r-bloggers.com/wp-admin/admin-ajax.php'; var snp_ajax_nonce = '7d1325bda5'; var snp_ignore_cookies = false; var snp_enable_analytics_events = false; var snp_enable_mobile = false; var snp_use_in_all = false; var snp_excluded_urls = []; snp_excluded_urls.push(''); Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.) Click here to close (This popup will not appear again) .snp-pop-109583 .snp-theme6 { max-width: 700px;} .snp-pop-109583 .snp-theme6 h1 {font-size: 17px;} .snp-pop-109583 .snp-theme6 { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field ::-webkit-input-placeholder { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field :-moz-placeholder { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field :-ms-input-placeholder { color: #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field input { border: 1px solid #a0a4a9;} .snp-pop-109583 .snp-theme6 .snp-field { color: #000000;} .snp-pop-109583 .snp-theme6 { background: #f2f2f2;} jQuery(document).ready(function() { }); var CaptchaCallback = function() { jQuery('.g-recaptcha').each(function(index, el) { grecaptcha.render(el, { 'sitekey' : '' }); }); }; (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "https://www.r-bloggers.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shCore.css?ver=3.0.9b"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.head.appendChild( corecss ); var themecssurl = "https://www.r-bloggers.com/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shThemeDefault.css?ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } document.head.appendChild( themecss ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['pad-line-numbers'] = false; SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); // Infinite scroll support if ( typeof( jQuery ) !== 'undefined' ) { jQuery( function( \$ ) { \$( document.body ).on( 'post-load', function() { SyntaxHighlighter.highlight(); } ); } ); } _stq = window._stq || []; _stq.push([ 'view', {v:'ext',j:'1:7.3.2',blog:'11524731',post:'196709',tz:'-6',srv:'www.r-bloggers.com'} ]); _stq.push([ 'clickTrackerInit', '11524731', '196709' ]); jQuery(document).ready(function (\$) { //\$( document ).ajaxStart(function() { //}); for (var i = 0; i < document.forms.length; ++i) { var form = document.forms[i]; if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="jIBkaqQVHTl" value="oCAPh9pY4Iy" />'); } if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="cgSbLnGDmuop" value="0ymqxuI5tUKJ" />'); } if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="lbnHGIegTFXc" value="hw1t.gx[]HkX" />'); } if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="ZVuvrLMsGE_Xd" value="jA92xkTbXp]@l" />'); } } \$(document).on('submit', 'form', function () { if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="jIBkaqQVHTl" value="oCAPh9pY4Iy" />'); } if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="cgSbLnGDmuop" value="0ymqxuI5tUKJ" />'); } if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="lbnHGIegTFXc" value="hw1t.gx[]HkX" />'); } if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="ZVuvrLMsGE_Xd" value="jA92xkTbXp]@l" />'); } return true; }); jQuery.ajaxSetup({ beforeSend: function (e, data) { //console.log(Object.getOwnPropertyNames(data).sort()); //console.log(data.type); if (data.type !== 'POST') return; if (typeof data.data === 'object' && data.data !== null) { data.data.append("jIBkaqQVHTl", "oCAPh9pY4Iy"); data.data.append("cgSbLnGDmuop", "0ymqxuI5tUKJ"); data.data.append("lbnHGIegTFXc", "hw1t.gx[]HkX"); data.data.append("ZVuvrLMsGE_Xd", "jA92xkTbXp]@l"); } else { data.data = data.data + '&jIBkaqQVHTl=oCAPh9pY4Iy&cgSbLnGDmuop=0ymqxuI5tUKJ&lbnHGIegTFXc=hw1t.gx[]HkX&ZVuvrLMsGE_Xd=jA92xkTbXp]@l'; } } }); }); /* <![CDATA[ */ jQuery(function(){ jQuery("ul.sf-menu").supersubs({ minWidth: 12, maxWidth: 27, extraWidth: 1 }).superfish({ delay: 100, speed: 250 }); }); /* ]]> */ ```