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
  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
 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 `

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
 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
  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
 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  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; // s.defer = true; // s.src = '//cdn.viglink.com/api/vglnk.js'; s.src = 'https://www.r-bloggers.com/wp-content/uploads/2020/08/vglnk.js'; var r = d.getElementsByTagName(t); r.parentNode.insertBefore(s, r); }(document, 'script')); Related ShareTweet To leave a comment for the author, please follow the link and comment on their blog: Quantargo Blog. R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job. Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. ```
``` ```
``` ```
```  function init() { var vidDefer = document.getElementsByTagName('iframe'); for (var i=0; i<vidDefer.length; i++) { if(vidDefer[i].getAttribute('data-src')) { vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src')); } } } window.onload = init; R bloggers Facebook page Most viewed posts (weekly) 5 Ways to Subset a Data Frame in R How to write the first for loop in R Date Formats in R R – Sorting a data frame by the contents of a column The fastest way to Read and Writes file in R Generalized Linear Models and Plots with edgeR – Advanced Differential Expression Analysis How to Remove Outliers in R 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); } // no longer use async because of google // async 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"); Recent Posts Building a Simple Pipeline in R Building apps with {shinipsum} and {golem} Slicing the onion 3 ways- Toy problems in R, python, and Julia path.chain: Concise Structure for Chainable Paths Generalized Linear Models and Plots with edgeR – Advanced Differential Expression Analysis National Weekly Death Rates Kmeans Clustering of Penguins Running an R Script on a Schedule: Overview Free workshop on Deep Learning with Keras and TensorFlow Le Monde puzzle [#1155] The fastest way to Read and Writes file in R Why R? 2020 Conference Starts 2020-09-26 Free text in surveys – important issues in the 2017 New Zealand Election Study by @ellis2013nz Lessons learned from 500+ Data Science interviews Writing conundrums Jobs for R-usersJunior Data Scientist / Quantitative economistSenior Quantitative AnalystR programmerData Scientist – CGIAR Excellence in Agronomy (Ref No: DDG-R4D/DS/1/CG/EA/06/20)Data Analytics Auditor, Future of Audit Lead @ London or Newcastle python-bloggers.com (python/data-science news)Writing conundrumsIntroducing Unguided Projects: The World’s First Interactive Code-Along ExercisesDocument Letter Frequency in PythonEquipping Petroleum Engineers in Calgary With Critical Data SkillsConnecting Python to SQL Server using trusted and login credentialsIntro to GSC API with Python (Video)Technical documentation Full list of contributing R-bloggers Archives Archives Select Month September 2020  (162) August 2020  (180) July 2020  (229) June 2020  (204) May 2020  (285) April 2020  (292) March 2020  (246) February 2020  (219) January 2020  (213) December 2019  (215) November 2019  (193) October 2019  (216) September 2019  (211) August 2019  (256) July 2019  (228) June 2019  (218) May 2019  (250) April 2019  (275) March 2019  (295) February 2019  (255) January 2019  (281) December 2018  (252) November 2018  (285) October 2018  (308) September 2018  (291) August 2018  (270) July 2018  (333) June 2018  (298) May 2018  (321) April 2018  (301) March 2018  (291) February 2018  (241) January 2018  (330) December 2017  (261) November 2017  (270) October 2017  (290) September 2017  (294) August 2017  (340) July 2017  (283) June 2017  (317) May 2017  (349) April 2017  (324) March 2017  (365) February 2017  (317) January 2017  (367) December 2016  (347) November 2016  (294) October 2016  (306) September 2016  (254) August 2016  (287) July 2016  (326) June 2016  (263) May 2016  (292) April 2016  (260) March 2016  (302) February 2016  (268) January 2016  (337) December 2015  (304) November 2015  (234) October 2015  (259) September 2015  (238) August 2015  (264) July 2015  (243) June 2015  (213) May 2015  (235) April 2015  (211) March 2015  (259) February 2015  (212) January 2015  (245) December 2014  (236) November 2014  (221) October 2014  (218) September 2014  (259) August 2014  (217) July 2014  (235) June 2014  (241) May 2014  (243) April 2014  (260) March 2014  (289) February 2014  (269) January 2014  (263) December 2013  (264) November 2013  (241) October 2013  (234) September 2013  (215) August 2013  (223) July 2013  (254) June 2013  (272) May 2013  (260) April 2013  (279) March 2013  (277) February 2013  (294) January 2013  (343) December 2012  (308) November 2012  (277) October 2012  (308) September 2012  (270) August 2012  (263) July 2012  (247) June 2012  (298) May 2012  (287) April 2012  (295) March 2012  (304) February 2012  (264) January 2012  (280) December 2011  (251) November 2011  (261) October 2011  (281) September 2011  (187) August 2011  (258) July 2011  (219) June 2011  (225) May 2011  (239) April 2011  (268) March 2011  (249) February 2011  (205) January 2011  (209) December 2010  (188) November 2010  (172) October 2010  (219) September 2010  (185) August 2010  (203) July 2010  (175) June 2010  (167) May 2010  (164) April 2010  (152) March 2010  (165) February 2010  (135) January 2010  (121) December 2009  (126) November 2009  (66) October 2009  (87) September 2009  (65) August 2009  (56) July 2009  (64) June 2009  (54) May 2009  (35) April 2009  (38) March 2009  (40) February 2009  (33) January 2009  (42) December 2008  (16) November 2008  (14) October 2008  (10) September 2008  (8) August 2008  (11) July 2008  (7) June 2008  (8) May 2008  (8) April 2008  (4) March 2008  (5) February 2008  (6) January 2008  (10) December 2007  (3) November 2007  (5) October 2007  (9) September 2007  (7) August 2007  (21) July 2007  (9) June 2007  (3) May 2007  (3) April 2007  (1) March 2007  (5) February 2007  (4) November 2006  (1) October 2006  (2) August 2006  (3) July 2006  (1) June 2006  (1) May 2006  (3) April 2006  (1) March 2006  (1) February 2006  (5) January 2006  (1) October 2005  (1) September 2005  (3) May 2005  (1) /* <![CDATA[ */ (function() { var dropdown = document.getElementById( "archives-dropdown-3" ); function onSelectChange() { if ( dropdown.options[ dropdown.selectedIndex ].value !== '' ) { document.location.href = this.options[ this.selectedIndex ].value; } } dropdown.onchange = onSelectChange; })(); /* ]]> */ Other sites Jobs for R-users SAS blogs ```
``` ```
``` Copyright © 2020 | MH Corporate basic by MH Themes ```
``` [{"@context":"https:\/\/schema.org","@graph":[{"@type":"Organization","@id":"https:\/\/www.r-bloggers.com#Organization","name":"R-bloggers","url":"http:\/\/www.r-bloggers.com","sameAs":[],"logo":{"@type":"ImageObject","url":"http:\/\/www.r-bloggers.com\/wp-content\/uploads\/2020\/07\/R_blogger_logo_02.png","width":"1061","height":"304"},"contactPoint":{"@type":"ContactPoint","contactType":"technical support","telephone":"","url":"https:\/\/www.r-bloggers.com\/contact-us\/"}},{"@type":"WebSite","@id":"https:\/\/www.r-bloggers.com#website","headline":"R-bloggers","name":"R-bloggers","description":"R news and tutorials contributed by hundreds of R bloggers","url":"https:\/\/www.r-bloggers.com","potentialAction":{"@type":"SearchAction","target":"https:\/\/www.r-bloggers.com\/?s={search_term_string}","query-input":"required name=search_term_string"},"publisher":{"@id":"https:\/\/www.r-bloggers.com#Organization"}},{"@context":"https:\/\/schema.org","@type":"WebPage","@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#webpage","name":"Use basic operators | R-bloggers","url":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/","lastReviewed":"2020-05-08T05:31:23-06:00","reviewedBy":{"@type":"Organization","logo":{"@type":"ImageObject","url":"http:\/\/www.r-bloggers.com\/wp-content\/uploads\/2020\/07\/R_blogger_logo_02.png","width":"1061","height":"304"},"name":"R-bloggers"},"inLanguage":"en-US","description":"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.\n\nUse R as a pocket calculator\nUse arithmetic operators on vectors\nUse relational operators on vectors\nUse logical operators on vectors\n\n___ + ___\n___ - ___\n___ \/ ___\n___ * ___\n___ ^ ___\n\n___ == ___\n___ != ___\n___ ___\n___ = ___\n\n___ &amp; ___\n___ | ___\n\n___ %in% ___\nUsing R as a pocket calculator\n___ + ___\n___ - ___\n___ \/ ___\n___ * ___\nR 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:\n5 + 5\n 10\n7 - 3.5\n 3.5\nSimilarly, you can multiply * or divide \/ numbers:\n5 * 7\n 35\n8 \/ 4\n 2\nYou can take the power of a number by using the ^ sign:\n2 ^ 3\n 8\nAccording to the rules of mathematics, you can use round brackets to specify the order of evaluation in more complex tasks:\n5 * (2 + 4 \/ 2)\n 20\nExercise: Use basic arithmetic\nTo calculate the mean of the numbers 2, 3, 7 and 8:\n\nAdd all the numbers together using +.\nDivide the result by the number of elements.\nMake sure that the result of the addition is calculated first by using braces ().\n\nStart Exercise\nApplying arithmetic operators on vectors\n___ + ___\n___ - ___\n___ \/ ___\n___ * ___\nOperations, 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.\nIn the following example we create two numeric vectors and assign them to the variables a and b. We then add them together:\na \n 3 7 12 17 22 27\nAs 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.\nWe can apply any other arithmetic operation in a similar way:\na \n 5.5 2.0 3.5 0.5 1.0 0.5\nUsing the same principle, the first element of the result is 22 \/ 4 = 5.5, the second is 10 \/ 5 = 2 and so on.\nQuiz: Vector Multiplication\nodd \nInspect the code chunk above. What is the result of the multiplication?\n\n\n108\n54\n\n15, 48\n\n\n2, 12, 30\n\n\n18, 36, 54\n\n\nStart Quiz\nExercise: Multiply numeric vectors\nMultiply the numeric vectors ascending and descending:\n\nCreate a vector with the numbers 1, 2, 3 and 4 and assign it to the variable ascending.\nCreate a vector with the numbers 4, 3, 2 and 1 and assign it to the variable descending.\nMultiply (*) the variable ascending with the variable descending.\n\nStart Exercise\nUsing relational operators\n___ == ___\n___ != ___\n___ ___\n___ = ___\nRelational 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\u2019ll see below.\nThe equal == and not equal != operators check whether two values are the same (or not):\n2 == 1 + 1\n TRUE\n2 != 3\n TRUE\nThe less than &lt; and greater than &gt; operators check, whether a value is less or greater than another one:\n2 &gt; 4\n FALSE\n2 \n TRUE\nThe less than or equal to &lt;= and the greater than or equal to &gt;= operators combine the check for equality with either the less or the greater than comparison:\n2 &gt;= 2\n TRUE\n2 \n TRUE\nAll 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:\nvector1 vector2\n TRUE FALSE FALSE TRUE FALSE TRUE\nTherefore, the output of this example is based on the comparisons 3 &gt; 2, 5 &gt; 6, 2 &gt; 3 and so on.\nExercise: Compare numeric values\nUse the appropriate relational operator and check whether 3 is greater than or equal to 2\nStart Exercise\nExercise: Compare temperatures\nIn 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. \nUse an appropriate relational operator and check in which months there was an increase in the average temperature.\nStart Exercise\nUsing logical operators\n___ &amp; ___\n___ | ___\nThe AND operator &amp; 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:\n3 &gt; 1 &amp; 4 \n FALSE\n3 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.\nThe OR operator | checks only, whether any of the statements is TRUE. \n3 &gt; 1 | 4 \n TRUE\nIn 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.\nThe ! 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:\n!3 &gt; 2\n FALSE\nLogical 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.\na b &amp; b FALSE TRUE FALSE FALSE\nFirst, both relational comparisons a&gt;b and b&lt;c are evaluated and result in two logical vectors. Therefore, we essentially compare the following two vectors:\nc(FALSE, TRUE, FALSE, TRUE) &amp; c(FALSE, TRUE, FALSE, FALSE)\n FALSE TRUE FALSE FALSE\nThe &amp; 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.\nThe | operator checks whether any of the values at the same position in the vectors is TRUE.\nc(FALSE, TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE, FALSE)\n FALSE TRUE FALSE TRUE\nExercise: Use the &amp; operator\nYou 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.\nStart Exercise\nExercise: Use the | operator\nYou 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 |) \nStart Exercise\nUsing the %in% operator\n___ %in% ___\nOne 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.\nIn 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.\nEU \n TRUE\nThe 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:\nc(\"AU\",\"HU\",\"UK\") %in% EU\n TRUE TRUE FALSE\nAs the output shows, the first two character elements \"AU\" and \"HU\" are present in the variable EU, however the third element \"UK\" is not.\nExercise: Use the %in% operator\nYou are standing in the supermarket and need to determine which you can check-off your shopping_list:\n\n\nUse the %in% operator and determine which shopping_list items you can check-off your list based on the items in your basket.\nPrint the output of the resulting vector to the console.\n\nStart Exercise\nUse basic operators is an excerpt from the course Introduction to R, which is available for free on quantargo.com\nVIEW FULL COURSE","primaryImageOfPage":{"@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#primaryimage"},"mainContentOfPage":[[{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"Home","url":"https:\/\/www.r-bloggers.com"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"About","url":"http:\/\/www.r-bloggers.com\/about\/"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"RSS","url":"https:\/\/feeds.feedburner.com\/RBloggers"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"add your blog!","url":"http:\/\/www.r-bloggers.com\/add-your-blog\/"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"Learn R","url":"https:\/\/www.r-bloggers.com\/how-to-learn-r-2\/"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"R jobs","url":"https:\/\/www.r-users.com\/"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"Submit a new job (it's free)","url":"https:\/\/www.r-users.com\/submit-job\/"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"Browse latest jobs (also free)","url":"https:\/\/www.r-users.com\/"},{"@context":"https:\/\/schema.org","@type":"SiteNavigationElement","@id":"https:\/\/www.r-bloggers.com\/#top nav","name":"Contact us","url":"http:\/\/www.r-bloggers.com\/contact-us\/"}]],"isPartOf":{"@id":"https:\/\/www.r-bloggers.com#website"},"breadcrumb":{"@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#breadcrumb"}},{"@type":"BreadcrumbList","@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"https:\/\/www.r-bloggers.com","name":"R-bloggers"}},{"@type":"ListItem","position":2,"item":{"@id":"https:\/\/www.r-bloggers.com\/category\/r-bloggers\/","name":"R bloggers"}},{"@type":"ListItem","position":3,"item":{"@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/","name":"Use basic operators | R-bloggers"}}]},{"@type":"Article","@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#article","url":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/","inLanguage":"en-US","mainEntityOfPage":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#webpage","headline":"Use basic operators | R-bloggers","description":"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.\n\nUse R as a pocket calculator\nUse arithmetic operators on vectors\nUse relational operators on vectors\nUse logical operators on vectors\n\n___ + ___\n___ - ___\n___ \/ ___\n___ * ___\n___ ^ ___\n\n___ == ___\n___ != ___\n___ ___\n___ = ___\n\n___ &amp; ___\n___ | ___\n\n___ %in% ___\nUsing R as a pocket calculator\n___ + ___\n___ - ___\n___ \/ ___\n___ * ___\nR 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:\n5 + 5\n 10\n7 - 3.5\n 3.5\nSimilarly, you can multiply * or divide \/ numbers:\n5 * 7\n 35\n8 \/ 4\n 2\nYou can take the power of a number by using the ^ sign:\n2 ^ 3\n 8\nAccording to the rules of mathematics, you can use round brackets to specify the order of evaluation in more complex tasks:\n5 * (2 + 4 \/ 2)\n 20\nExercise: Use basic arithmetic\nTo calculate the mean of the numbers 2, 3, 7 and 8:\n\nAdd all the numbers together using +.\nDivide the result by the number of elements.\nMake sure that the result of the addition is calculated first by using braces ().\n\nStart Exercise\nApplying arithmetic operators on vectors\n___ + ___\n___ - ___\n___ \/ ___\n___ * ___\nOperations, 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.\nIn the following example we create two numeric vectors and assign them to the variables a and b. We then add them together:\na \n 3 7 12 17 22 27\nAs 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.\nWe can apply any other arithmetic operation in a similar way:\na \n 5.5 2.0 3.5 0.5 1.0 0.5\nUsing the same principle, the first element of the result is 22 \/ 4 = 5.5, the second is 10 \/ 5 = 2 and so on.\nQuiz: Vector Multiplication\nodd \nInspect the code chunk above. What is the result of the multiplication?\n\n\n108\n54\n\n15, 48\n\n\n2, 12, 30\n\n\n18, 36, 54\n\n\nStart Quiz\nExercise: Multiply numeric vectors\nMultiply the numeric vectors ascending and descending:\n\nCreate a vector with the numbers 1, 2, 3 and 4 and assign it to the variable ascending.\nCreate a vector with the numbers 4, 3, 2 and 1 and assign it to the variable descending.\nMultiply (*) the variable ascending with the variable descending.\n\nStart Exercise\nUsing relational operators\n___ == ___\n___ != ___\n___ ___\n___ = ___\nRelational 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\u2019ll see below.\nThe equal == and not equal != operators check whether two values are the same (or not):\n2 == 1 + 1\n TRUE\n2 != 3\n TRUE\nThe less than &lt; and greater than &gt; operators check, whether a value is less or greater than another one:\n2 &gt; 4\n FALSE\n2 \n TRUE\nThe less than or equal to &lt;= and the greater than or equal to &gt;= operators combine the check for equality with either the less or the greater than comparison:\n2 &gt;= 2\n TRUE\n2 \n TRUE\nAll 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:\nvector1 vector2\n TRUE FALSE FALSE TRUE FALSE TRUE\nTherefore, the output of this example is based on the comparisons 3 &gt; 2, 5 &gt; 6, 2 &gt; 3 and so on.\nExercise: Compare numeric values\nUse the appropriate relational operator and check whether 3 is greater than or equal to 2\nStart Exercise\nExercise: Compare temperatures\nIn 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. \nUse an appropriate relational operator and check in which months there was an increase in the average temperature.\nStart Exercise\nUsing logical operators\n___ &amp; ___\n___ | ___\nThe AND operator &amp; 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:\n3 &gt; 1 &amp; 4 \n FALSE\n3 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.\nThe OR operator | checks only, whether any of the statements is TRUE. \n3 &gt; 1 | 4 \n TRUE\nIn 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.\nThe ! 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:\n!3 &gt; 2\n FALSE\nLogical 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.\na b &amp; b FALSE TRUE FALSE FALSE\nFirst, both relational comparisons a&gt;b and b&lt;c are evaluated and result in two logical vectors. Therefore, we essentially compare the following two vectors:\nc(FALSE, TRUE, FALSE, TRUE) &amp; c(FALSE, TRUE, FALSE, FALSE)\n FALSE TRUE FALSE FALSE\nThe &amp; 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.\nThe | operator checks whether any of the values at the same position in the vectors is TRUE.\nc(FALSE, TRUE, FALSE, TRUE) | c(FALSE, TRUE, FALSE, FALSE)\n FALSE TRUE FALSE TRUE\nExercise: Use the &amp; operator\nYou 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.\nStart Exercise\nExercise: Use the | operator\nYou 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 |) \nStart Exercise\nUsing the %in% operator\n___ %in% ___\nOne 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.\nIn 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.\nEU \n TRUE\nThe 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:\nc(\"AU\",\"HU\",\"UK\") %in% EU\n TRUE TRUE FALSE\nAs the output shows, the first two character elements \"AU\" and \"HU\" are present in the variable EU, however the third element \"UK\" is not.\nExercise: Use the %in% operator\nYou are standing in the supermarket and need to determine which you can check-off your shopping_list:\n\n\nUse the %in% operator and determine which shopping_list items you can check-off your list based on the items in your basket.\nPrint the output of the resulting vector to the console.\n\nStart Exercise\nUse basic operators is an excerpt from the course Introduction to R, which is available for free on quantargo.com\nVIEW FULL COURSE","articleBody":"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: Add all the numbers together using +. Divide the result by the number of elements. 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","keywords":"","datePublished":"2020-05-08T05:31:23-06:00","dateModified":"2020-05-08T05:31:23-06:00","author":{"@type":"Person","name":"Quantargo Blog","description":"","url":"https:\/\/www.r-bloggers.com\/author\/quantargo-blog\/","sameAs":["\/"],"image":{"@type":"ImageObject","url":"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g","height":96,"width":96}},"publisher":{"@id":"https:\/\/www.r-bloggers.com#Organization"},"image":[{"@type":"ImageObject","url":"https:\/\/www.quantargo.com\/assets\/courses\/course-r-introduction\/01-basics\/04-operators.png","width":1200,"height":630,"@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#primaryimage"}],"isPartOf":{"@id":"https:\/\/www.r-bloggers.com\/2020\/05\/use-basic-operators\/#webpage"}}]}] 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 = '381996bdf4'; 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' : '' }); }); }; /* <![CDATA[ */!function(e,n){var r={"selectors":{"block":"pre","inline":"code"},"options":{"indent":4,"ampersandCleanup":true,"linehover":true,"rawcodeDbclick":false,"textOverflow":"scroll","linenumbers":false,"theme":"enlighter","language":"r","retainCssClasses":false,"collapse":false,"toolbarOuter":"","toolbarTop":"{BTN_RAW}{BTN_COPY}{BTN_WINDOW}{BTN_WEBSITE}","toolbarBottom":""},"resources":["https:\/\/www.r-bloggers.com\/wp-content\/plugins\/enlighter\/cache\/enlighterjs.min.css?vVCnEZeurtkU0vr","https:\/\/www.r-bloggers.com\/wp-content\/plugins\/enlighter\/\/resources\/enlighterjs\/enlighterjs.min.js"]},o=document.getElementsByTagName("head"),t=n&&(n.error||n.log)||function(){};e.EnlighterJSINIT=function(){!function(e,n){var r=0,l=null;function c(o){l=o,++r==e.length&&(!0,n(l))}e.forEach(function(e){switch(e.match(/\.([a-z]+)(?:[#?].*)?\$/)){case"js":var n=document.createElement("script");n.onload=function(){c(null)},n.onerror=c,n.src=e,n.async=!0,o.appendChild(n);break;case"css":var r=document.createElement("link");r.onload=function(){c(null)},r.onerror=c,r.rel="stylesheet",r.type="text/css",r.href=e,r.media="all",o.appendChild(r);break;default:t("Error: invalid file extension",e)}})}(r.resources,function(e){e?t("Error: failed to dynamically load EnlighterJS resources!",e):"undefined"!=typeof EnlighterJS?EnlighterJS.init(r.selectors.block,r.selectors.inline,r.options):t("Error: EnlighterJS resources not loaded yet!")})},(document.querySelector(r.selectors.block)||document.querySelector(r.selectors.inline))&&e.EnlighterJSINIT()}(window,console); /* ]]> */ window.FPConfig= { delay: 0, ignoreKeywords: ["\/wp-admin","\/wp-login.php","\/cart","add-to-cart","logout","#","?",".png",".jpeg",".jpg",".gif",".svg"], maxRPS: 3, hoverDelay: 50 }; _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="PnM-zH_AKJNfBeFs" value="v*TMZOlu5zynohG6" />'); } if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="-cRxUiIS" value="6UaC7c1T" />'); } if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="VXUxhtONi" value="Nc8akts2n" />'); } if (\$(form).attr("method") != "get") { \$(form).append('<input type="hidden" name="GyoDAYLMZ" value="yE2gzT5Zm" />'); } } \$(document).on('submit', 'form', function () { if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="PnM-zH_AKJNfBeFs" value="v*TMZOlu5zynohG6" />'); } if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="-cRxUiIS" value="6UaC7c1T" />'); } if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="VXUxhtONi" value="Nc8akts2n" />'); } if (\$(this).attr("method") != "get") { \$(this).append('<input type="hidden" name="GyoDAYLMZ" value="yE2gzT5Zm" />'); } 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("PnM-zH_AKJNfBeFs", "v*TMZOlu5zynohG6"); data.data.append("-cRxUiIS", "6UaC7c1T"); data.data.append("VXUxhtONi", "Nc8akts2n"); data.data.append("GyoDAYLMZ", "yE2gzT5Zm"); } else { data.data = data.data + '&PnM-zH_AKJNfBeFs=v*TMZOlu5zynohG6&-cRxUiIS=6UaC7c1T&VXUxhtONi=Nc8akts2n&GyoDAYLMZ=yE2gzT5Zm'; } } }); }); ```