2+4
#> [1] 6
When you type something into the console, R will give you a reply. For example:
As expected, R returned 6
.
Note:
[1]
you see in the output. It simply means that 6
is the “first element of the line.”R can also be used as a calculator.
Note:
Description | Operator |
---|---|
Addition | + |
Subtraction | - |
Multiplication | * |
Division | / |
Exponentiation | ^ or ** |
Integer division | x %/% y (e.g., 10%/%3 is 3) |
Modulus (remainder) | x %% y (e.g., 10%%3 is 1) |
Notice
These calculations do not create objects that are remembered by R.
To store calculations in R, we assign them to objects.
Assignment operators <-
or =
can be used, but <-
is preferred because =
has other uses.
Now that we’ve created this object, R will remember it during the current session.
All created objects are stored in the current workspace. In RStudio, you can see them under the Environment
tab (top right pane).
Objects can hold different types of values. For example:
Here we created my_obj2
, which stores a character string "R is cool"
.
my_obj
and my_obj2
.To change the value of an existing object, reassign it:
Now my_obj2
holds a numeric value instead of a string.
You can perform operations using objects. For example:
This creates my_obj3
with value 48+1024=1072.
If you try adding two character strings:
R will return an error because strings cannot be added.
Another common error is object * not found
.
Here, no_obj
has not been created, so the operation fails.
a-z
, A-Z
)0-9
).
and underscore _
-
, or underscore _
.mean
, log
, exp
, TRUE
, c
, etc.).x1
with value 73.x2
as the result of 101+36.x1
and x2
and store it in x3
.x3
and calculate its 4th root.Parentheses ( )
are used to group expressions. They must be matched.
Curly braces { }
do not cause errors in expressions but have special uses (e.g., functions).
Square brackets [ ]
are used for indexing, not arithmetic:
Description | Function | Example |
---|---|---|
Square root | sqrt |
sqrt(225) |
Natural log | log |
log(50) |
Exponential | exp |
exp(3) |
Absolute value | abs |
abs(-10) |
Factorial | factorial |
factorial(6) |
Sine function | sin |
sin(25) |
Inverse cosine | acos |
acos(-1) |
General function structure:
Example:
Both return 5
.
Note
( )
.You can add spaces freely between elements.
But spaces inside a value cause errors:
Use #
to write comments. R ignores everything after #
.
Instead of typing code line by line, you can save it in a script (.R
file).
Note
source("C:/Users/Rasel/Documents/my_script.R")
Tip
source()
runs inside your current R session (objects remain).Rscript
runs in a fresh session (objects do not remain).Why does this code not work?
myObject
with a value between 1 and 100.myObject
and update the object.myObject
is divisible by 2, 3, 13, or 21.myObject
?Save this code into practice.R
:
Run it with source("practice.R")
(R Console).
Run it with Rscript practice.R
(Terminal).