2.1 Use R as a calculator - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
Video transcript
<v Voiceover>Being a</v> statistical programming language, R excels at all things math, whether it's complicated linear algebra or simple addition and subtraction. To show some of this, let's open up a new text editor area by clicking Control + Shift + N and saving it by using Control + S on your keyboard. We can name it BasicMath.r. So in here, simple things first such as one plus one, hitting Control + Enter puts in the console and you get two, much as expected. Now, a little more complex than that, you could string three of these together, such as one plus two plus three which should get us six. This can go on so forth and so on. Same thing with subtraction. Seven minus five. And of course you can string these things together. Eight plus nine minus six. All that basic math works. Similarly, multiplication. Three times four gets 12. And again, you can string them together. Four times three times two gets 24. Division is similar. Four divided by two gets two. However, that gave us back an integer result. Now let's say we were to divide four by three. Basic math tells us that should not give us an integer, that should leave us with a decimal and accordingly, R does that for us. Other programming languages, when you do division, it only gives you the integer portion. In R, it's for statistics. It's for numerical computation. It gives you the entire number, the entire decimal. However, being math, we do have to worry about complex expressions. Sometimes you might put together a formula and you need to understand in what order R is going to compute that. Fortunately, R follows the standard PEMDAS rules. That's P-E-M-D-A-S, PEMDAS. That's parentheses, exponents, multiplication, division, addition and subtraction. So, for instance, putting in four times six plus five should yield 29. That's because R first multiplied four and six, then took that result and added five. That makes sense because multiplication comes before addition. Now however, if you wanted to add six and five and then multiply that result by four, you need to use a grouping parentheses. That's four times, open the parentheses, six plus five and that gets you a very different result. You may notice the use of white space here. That is purely optional. Over here I didn't put any white space around the asterisk, but I did around the plus sign. That's just my personal coding style. This easily could have computed, I will take this and copy it, and I will run it again. This time I will get rid of the white space. Same exact answer. The only time when white space might be an issue is when assigning variables or arguments in a function and we will cover that, but generally, white space is completely optional. As long as you follow the rules of PEMDAS, and/or use explicit parentheses, you should be safe with your formulas.