Calculation and Variables#
R as calculator#
Using R at its most basic, it is a calculator. You can enter a calculation into the console and immediately evaluate the result.
# R is a calculator
1 + 2
3 * 4
Variables#
A core concept in programming, a variable is essentially a named piece of data. That is, when you refer to the variable by its name within the program, you are actually referring to the data stored under that name.
To assign data to a variable in R, use the following syntax:
# Assignment
x <- 2
y <- 3.5
After you have assigned data to variables, you can then use the variables to perform calculations:
# R is a clever calculator
x + 2
x * y
z <- x + x + x
If you need to see the value of a variable in the command line, you can just type its name:
# What is x?
x
Note that variable names are case sensitive, and cannot start with a number.
Exercise 0.1
Experiment for yourself with the R command line to do some simple calculations
## At this stage , the main point is to write in the R console . You can try the lines under the R as a calculator section.
Assign some different numbers to the variables x and y and check if calculations with them work as you expect
#At this stage , the main ail is to create your first R script and writing the commands their . You can try the lines under variable subsection
Try to do a calculation with a variable you haven’t assigned any data to, a for instance
# calculation with previously undeclared variable
a+x
Error: object 'a' not found
Set x to 1, then check what happens when you run the calculation x <- x + 1, what value is x afterwards?
# Set x to 1 and calculate
x <- 1
x <- x + 1
x
# 2 (autoincremants x as ++x)
Be aware that R has special values for certain calculations - try dividing by 0 for instance.
# Dividing by 0
x / 0
# Inf