3 Elements of the Language
There are certain concepts common to virtually all programming languages, which tell the computer how to behave. Those elements are: variables, functions and operators. This chapter will discuss what those are and how they’re implemented in R. By the end of this chapter, you will be able to answer the following:
- What is a variable and how do I create and modify them?
- How do functions work?
- How can I use logic to control what commends get executed?
If you’re familiar with other languages like Visual Basic, Python or Java Script, you may be tempted to skip this section. If you do, you’ll survive, but I’d suggest giving it a quick read. You may learn something about how R differs from those other languages.
3.1 Variables
Programming languages work by assigning values to space in your computer’s memory. Those values are then available for computation. Because the value of what’s stored in memory may “vary”, we call these things “variables”. Think of a cell in a spreadsheet. Before we put something in it, it’s just an empty box. We can fill it with whatever we like, be it a person’s name, their birthdate, their age, whatever.
3.1.1 Assignment
Assignment will create a variable which contains a value. This value may be used later.
r <- 4
r + 2
#> [1] 6
Both “<-” and “=” will work for assignment.
3.2 Operators
3.2.1 Mathematical Operators
Operator | Operation |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
^ | Exponentiation |
3.2.2 Logical Operators
Operator | Operation |
---|---|
& | and |
| | or |
! | not |
== | equal |
!= | not equal |
< | less than |
<= | less than or equal |
> | greater than |
>= | greater than or equal |
xor() | exclusive or |
&& | non-vector and |
|| | non-vector or |
3.3 Functions
Functions in R are very similar to functions in a spreadsheet. The function takes in arguments and returns a result.
sqrt(4)
#> [1] 2
Functions may be composed by having the output of one serve as the input to another.
\(\sqrt{e^{sin{\pi}}}\)
sqrt(exp(sin(pi)))
#> [1] 1
3.3.1 A few mathematical functions
?S3groupGeneric
- abs, sign
- floor, ceiling, trunc, round, signif
- sqrt, exp, log
- cos, sin, tan (and many others)
- lgamma, gamma, digamma, trigamma
3.5 Exercises
- What is the area of a cylinder with radius = e and height = pi?
- What arguments are listed for the “plot” function?
- Find the help file for a generalized linear model
- Create a script which calculates the area of a cylinder. From a new script, assign the value 4 to a variable and source the other file. Assign the value 8 to your variable and source again. What happened?
3.4 Comments
R uses the hash/pound character “#” to indicate comments.
SQL or C++ style multiline comments are not supported.
Comment early and often!
Comments should describe “why”, not “what”.
3.4.1 Bad comment
3.4.2 Good comment