styler
packagescale()
At its core, R (like all programming languages) is basically a fancy calculator. The syntax of most basic arithmetic operations in R should be familiar to you:
1 + 2 # addition
1] 3
[3 - 2 # subtraction
1] 1
[4 * 2 # multiplication
1] 8
[4 / 2 # division
1] 2
[1.234 + 2.345 - 3.5*4.9 # numbers can have decimals
1] -13.571
[1.234 + (2.345 - 3.5)*4.9 # expressions can contain parentheses
1] -4.4255
[2**2 # exponentiation
1] 4
[4**(1/2) # square root
1] 2
[9**(1/3) # cube root
1] 3 [
The [1]
lines above are the output given by R when the preceding expression
is executed. Any portion of a line starting with a #
is a comment and ignored
by R.
R also supports storing values into symbolic placeholders called variables, or
objects. An expression like those above can be assigned into a variable with a
name using the <-
operator:
<- 1 + 2 new_var
Variables that have been assigned a value can be placed in subsequent expressions anywhere where their value is evaluated:
- 2
new_var 1] 1
[<- new_var * 4 another_var
The correct way to assign a value to a variable in R is with the <-
syntax,
unlike many other programming languages which use =
. However, although the =
assignment syntax does work in R:
= 2 # works, but is not common convention! new_var
this is considered bad practice and may cause confusion later. You should always
use the <-
syntax when assigning values to variables!
In R, the period .
does not have a special meaning like it does in many other
languages like python, C, javascript, etc. Therefore, new.var
is a valid
variable name just like new_var
, even though it may look strange to those
familiar with these other languages. While including .
in your R variable
names is valid, the results that you will use in programs written in other
languages that do have a meaning for this character. Therefore, it is good
practice to avoid using .
characters in your variable names to reduce the
chances of conflicts later.