1+2
[1] 3
1-2
[1] -1
1/2
[1] 0.5
1*2
[1] 2
2^3 # same as 2**3
[1] 8
All basic calculator operations can be performed in R.
1+2
[1] 3
1-2
[1] -1
1/2
[1] 0.5
1*2
[1] 2
2^3 # same as 2**3
[1] 8
For now, you can ignore the [1] at the beginning of the line, we’ll learn about that when we get to vectors.
Many advanced calculator operations are also available.
1+3)*2 + 100^2 # standard order of operations (PEMDAS) (
[1] 10008
sin(2*pi) # the result is in scientific notation, i.e. -2.449294 x 10^-16
[1] -2.449294e-16
sqrt(4)
[1] 2
log(10) # the default is base e
[1] 2.302585
log(10, base = 10)
[1] 1
A real advantage to using R rather than a calculator (or calculator app) is the ability to store quantities using variables.
= 1
a = 2
b + b a
[1] 3
- b a
[1] -1
/ b a
[1] 0.5
* b a
[1] 2
^ 3 b
[1] 8
R is a case sensitive language and therefore you need to be careful about capitalization.
<- 3
ThisObjectExists ThisObjectExists
[1] 3
# no it doesn't thisobjectexists
Error in eval(expr, envir, enclos): object 'thisobjectexists' not found
Valid object names “consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number”.
# Valid object names
= 1
a = 2 .b
# Invalid object names
2a = 3
2a = 4
.= 5 _c
Error: <text>:2:2: unexpected symbol
1: # Invalid object names
2: 2a
^
You cannot use any reserved names as object names, i.e. these names cannot be overwritten.
?Reserved
When assigning variables values, you can also use arrows <- and -> and you will often see this in code, e.g.
<- 1 # recommended
a 2 -> b # uncommon, but sometimes useful
= 3 # similar to other languages c
Now print them.
a
[1] 1
b
[1] 2
c
[1] 3
While using variables alone is useful, it is much more useful to use informative variables names.
# Rectangle
<- 4
length <- 3
width
<- length * width
area area
[1] 12
<- 2 * (length + width)
perimeter
# (Right) Triangle
<- 1
opposite <- 30
angleDegrees <- angleDegrees * pi/180
angleRadians
<- opposite / tan(angleRadians)) # = sqrt(3) (adjacent
[1] 1.732051
<- opposite / sin(angleRadians)) # = 2 (hypotenuse
[1] 2