Using R as a Calculator

Site: Saylor Academy
Course: PRDV420: Introduction to R Programming
Book: Using R as a Calculator
Printed by: Guest user
Date: Wednesday, May 14, 2025, 2:13 AM

Description

All complex analyses comprise sequences of multiple simple operations. To get acquainted with R and "build trust," please read about these operations you can implement in the R (RStudio) console and immediately see the results. Run the codes on your computer. Do you get the same outputs? Try changing some of the code to see how the outputs will change. You should be able to guess what kind of output you can get from any of these simple operations.

Introduction to R

Much of your time in R will be spent in the R interactive console. This is where you will run all of your code, and can be a useful environment to try out ideas before adding them to an R script file. This console in RStudio is the same as the one you would get if you typed in R in your command-line environment.

The first thing you will see in the R interactive session is a bunch of information, followed by a ">" and a blinking cursor. In many ways,  this is similar to the shell environment you learned about during the shell lessons: it operates on the same idea of a "Read, evaluate, print loop": you type in commands, R tries to execute them, and then returns a result.


Using R as a calculator

The simplest thing you could do with R is to do arithmetic:

1 + 100

Output
[1] 101


And R will print out the answer with a preceding "[1]". Don't worry about this for now; we'll explain that later. For now, think of it as indicating output.

If you type in an incomplete command, R will wait for you to complete it. If you are familiar with Unix Shell's bash, you may recognize this
behavior from bash.

> 1 +

Output
+


Any time you hit return, and the R session shows a "+" instead of a ">", it means it's waiting for you to complete the command. If you want to cancel a command, you can hit Esc, and RStudio will give you back the ">" prompt.


Tip: Canceling commands

If you're using R from the command line instead of from within RStudio, you need to use Ctrl+C instead of Esc to cancel the command. This applies to Mac users as well!

Canceling a command isn't only useful for killing incomplete commands: you can also use it to tell R to stop running code (for example if it's taking much longer than you expect), or to get rid of the code you're currently writing.


Source: The Carpentries, https://swcarpentry.github.io/r-novice-gapminder/01-rstudio-intro/index.html
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.

Order of Operations

When using R as a calculator, the order of operations is the same as you would have learned back in school.

From highest to lowest precedence:

  • Parentheses: (, )
  • Exponents: ^ or **
  • Multiply: *
  • Divide: /
  • Add: +
  • Subtract: -

3 + 5 * 2

Output
[1] 13


Use parentheses to group operations to force the order of evaluation if it differs from the default or to clarify what you intend.

(3 + 5) * 2

Output
[1] 16


This can get unwieldy when not needed but clarifies your intentions. Remember that others may later read your code.

(3 + (5 * (2 ^ 2))) # hard to read
  3 + 5 * 2 ^ 2       # clear, if you remember the rules
  3 + 5 * (2 ^ 2)     # if you forget some rules, this might help

The text after each line of code is called a "comment." Anything that follows after the hash (or octothorpe) symbol # is ignored by R when it executes code.

Really small or large numbers get a scientific notation:

2/10000

Output
[1] 2e-04


Which is shorthand for "multiplied by 10^XX". So 2e-4 is shorthand for 2 * 10^(-4).

You can write numbers in scientific notation too:

5e3  # Note the lack of minus here

Output
[1] 5000

Mathematical Functions

R has many built-in mathematical functions. To call a function, we can type its name, followed by open and closing parentheses. Functions take arguments as inputs; anything we type inside the parentheses of a function is considered an argument. The number of arguments can vary from none to multiple, depending on the function. For example:

getwd() #returns an absolute filepath

Doesn't require an argument, whereas, for the next set of mathematical functions, we will need to supply the function a value in order to compute the result.

sin(1)  # trigonometry functions

Output
[1] 0.841471

log(1)  # natural logarithm

Output
[1] 0

log10(10) # base-10 logarithm

Output
[1] 1

exp(0.5) # e^(1/2)

Output
[1] 1.648721


Don't worry about trying to remember every function in R. You can look them up on Google, or if you can remember the start of the function's name, use the tab completion in RStudio.

This is one advantage that RStudio has over R on its own, it has auto-completion abilities that allow you to more easily look up functions, their arguments, and the values that they take.

Typing a ? Before a command's name will open the help page for that command. When using RStudio, this will open the ‘Help' pane; if using R in the terminal, the help page will open in your browser. The help page will include a detailed description of the command and how it works. Scrolling to the bottom of the help page will usually show a collection of code examples that illustrate command usage. We'll go through an example later.


Comparing Things

We can also do comparisons in R:

1 == 1  # equality (note two equals signs, read as "is equal to")

Output
[1] TRUE
1 != 2  # inequality (read as "is not equal to")

Output
[1] TRUE


1 < 2  # less than

Output
[1] TRUE


1 <= 1  # less than or equal to

Output
[1] TRUE


1 > 0  # greater than

Output
[1] TRUE


1 >= -9 # greater than or equal to

Output
[1] TRUE



Tip: Comparing Numbers

A word of warning about comparing numbers: you should never use == to compare two numbers unless they are integers (a data type which can specifically represent only whole numbers).

Computers may only represent decimal numbers with a certain degree of precision, so two numbers which look the same when printed out by R, may actually have different underlying representations and therefore be different by a small margin of error (called Machine numeric tolerance).

Instead you should use the all.equal function.


Variables and Assignments

We can store values in variables using the assignment operator <-, like this:

x <- 1/40

Notice that the assignment does not print a value. Instead, we stored it for later in something called a variable. x now contains the value 0.025:

x

Output
[1] 0.025


More precisely, the stored value is a decimal approximation of this fraction called a floating point number.

Look for the Environment tab in the top right panel of RStudio, and you will see that x its value has appeared. Our variable x can be used in place of a number in any calculation that expects a number:

log(x)

Output
[1] -3.688879

Notice also that variables can be reassigned:

x <- 100

x is used to contain the value 0.025, and now it has the value 100.

Assignment values can contain the variable being assigned to:

x <- x + 1 #notice how RStudio updates its description of x on the top right tab
 y <- x * 2

The right-hand side of the assignment can be any valid R expression. The right-hand side is fully evaluated before the assignment occurs.

Variable names can contain letters, numbers, underscores, and periods but no spaces. They must start with a letter or a period followed by a letter (they cannot start with a number or an underscore). Variables beginning with a period are hidden variables. Different people use different conventions for long variable names, these include

  • periods.between.words
  • underscores_between_words
  • camelCaseToSeparateWords

What you use is up to you, but be consistent.

It is also possible to use the = operator for assignment:

x = 1/40

But this is much less common among R users. The most important thing is to be consistent with the operator you use. There are occasional places where it is less confusing to use <- than =, and it is the most common symbol used in the community. So the recommendation is to use <-.


Challenge 1

Which of the following are valid R variable names?

min_height
 max.height
 _age
 .mass
 MaxLength
 min-length
 2widths
 celsius2kelvin

Solution to Challenge 1

The following can be used as R variables:

min_height
 max.height
 MaxLength
 celsius2kelvin


The following creates a hidden variable:

.mass


The following will not be able to be used to create a variable

_age
min-length
2widths

Vectorization

One final thing to be aware of is that R is vectorized, meaning that variables and functions can have vectors as values. In contrast to physics and mathematics, a vector in R describes a set of values in a certain order of the same data type. For example:

1:5

Output
[1] 1 2 3 4 5
2^(1:5)

Output
[1]  2  4  8 16 32
x <- 1:5
2^x

Output
[1]  2  4  8 16 32


This is incredibly powerful; we will discuss this further in an upcoming lesson.

Managing Your Environment

You can use a few useful commands to interact with the R session.

ls will list all of the variables and functions stored in the global environment (your working R session):

ls()

Output
[1] "args"    "dest_md" "op"      "src_rmd" "x"       "y"      


Tip: hidden objects

Like in the shell, ls will hide any variables or functions starting with a "". by default. To list all objects, type ls(all.names=TRUE) instead

Note here that we didn't give any arguments to ls, but we still needed to give the parentheses to tell R to call the function.

If we type ls by itself, R prints a bunch of code instead of listing objects.

ls

Output
function (name, pos = -1L, envir = as.environment(pos), all.names = FALSE, 
    pattern, sorted = TRUE) 
{</span><span class="pln">
    </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(!</span><span class="pln">missing</span><span class="pun">(</span><span class="pln">name</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
        pos </span><span class="pun"><-</span><span class="pln"> tryCatch</span><span class="pun">(</span><span class="pln">name</span><span class="pun">,</span><span class="pln"> error </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">function</span><span class="pun">(</span><span class="pln">e</span><span class="pun">)</span><span class="pln"> e</span><span class="pun">)</span><span class="pln">
        </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">inherits</span><span class="pun">(</span><span class="pln">pos</span><span class="pun">,</span><span class="pln"> </span><span class="str">"error"</span><span class="pun">))</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
            name </span><span class="pun"><-</span><span class="pln"> substitute</span><span class="pun">(</span><span class="pln">name</span><span class="pun">)</span><span class="pln">
            </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(!</span><span class="kwd">is</span><span class="pun">.</span><span class="pln">character</span><span class="pun">(</span><span class="pln">name</span><span class="pun">))</span><span class="pln"> 
                name </span><span class="pun"><-</span><span class="pln"> deparse</span><span class="pun">(</span><span class="pln">name</span><span class="pun">)</span><span class="pln">
            warning</span><span class="pun">(</span><span class="pln">gettextf</span><span class="pun">(</span><span class="str">"%s converted to character string"</span><span class="pun">,</span><span class="pln"> 
                sQuote</span><span class="pun">(</span><span class="pln">name</span><span class="pun">)),</span><span class="pln"> domain </span><span class="pun">=</span><span class="pln"> NA</span><span class="pun">)</span><span class="pln">
            pos </span><span class="pun"><-</span><span class="pln"> name
        </span><span class="pun">}
    }
    all.names <- .Internal(ls(envir, all.names, sorted))
    if (!missing(pattern)) {</span><span class="pln">
        </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">((</span><span class="pln">ll </span><span class="pun"><-</span><span class="pln"> length</span><span class="pun">(</span><span class="pln">grep</span><span class="pun">(</span><span class="str">"["</span><span class="pun">,</span><span class="pln"> pattern</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">fixed</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> TRUE</span><span class="pun">)))</span><span class="pln"> </span><span class="pun">&&</span><span class="pln"> 
            ll </span><span class="pun">!=</span><span class="pln"> length</span><span class="pun">(</span><span class="pln">grep</span><span class="pun">(</span><span class="str">"]"</span><span class="pun">,</span><span class="pln"> pattern</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">fixed</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> TRUE</span><span class="pun">)))</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
            </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">pattern </span><span class="pun">==</span><span class="pln"> </span><span class="str">"["</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
                pattern </span><span class="pun"><-</span><span class="pln"> </span><span class="str">"\\ [ "</span><span class="pln">
                warning</span><span class="pun">(</span><span class="str">"replaced regular expression pattern '[' by  '\\\\ ['"</span><span class="pun">)</span><span class="pln">
            </span><span class="pun">}
            else if (length(grep("[^\\\\)\\(<-", pattern))) {</span><span class="pln">
                pattern </span><span class="pun"><-</span><span class="pln"> </span><span class="kwd">sub</span><span class="pun">(</span><span class="str">"\\(<-"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"\\\\\\(<-"</span><span class="pun">,</span><span class="pln"> pattern</span><span class="pun">)</span><span class="pln">
                warning</span><span class="pun">(</span><span class="str">"replaced '[<-' by '\\\\(<-' in regular expression pattern"</span><span class="pun">)</span><span class="pln">
            </span><span class="pun">}
        }
        grep(pattern, all.names, value = TRUE)
    }
    else all.names
}
<bytecode: 0x55abdef9e9c8>
<environment: namespace:base>


What's going on here?

Like everything in R, ls is the name of an object, and entering the name of an object by itself prints the contents of the object. The object x that we created earlier contains 1, 2, 3, 4, 5:

x

Output
[1] 1 2 3 4 5

The object ls contains the R code that makes the ls function work! We'll talk more about how functions work and start writing our own later.

You can use rm to delete objects you no longer need:

rm(x)

If you have lots of things in your environment and want to delete all of them, you can pass the results of ls to the rm function:

rm(list = ls())

In this case, we've combined the two. Like the order of operations, anything inside the innermost parentheses is evaluated first, and so on.

In this case, we've specified that the results of ls should be used for the list argument in rm. When assigning values to arguments by name, you must use the = operator!!

If instead, we use <-, there will be unintended side effects, or you may get an error message:

rm(list <- ls())

Error
Error in rm(list <- ls()): ... must contain names or character strings


Tip: Warnings vs. Errors

Pay attention when R does something unexpected! Errors, like above, are thrown when R cannot proceed with a calculation. Warnings on the other hand usually mean that the function has run, but it probably hasn't worked as expected.

In both cases, the message that R prints out usually give you clues how to fix a problem.