1+1
[1] 2
R can serve as a simple calculator, for simple or more advanced operations.
Try the following commands
1+1
[1] 2
The output should be visible in your console.
Let’s try to calculate \(\frac{5 \times 4}{2}\) using R
5 * 4)/2 (
[1] 10
The most common operations in R
are listed below
Operation | R symbol |
---|---|
addition | + |
subtraction | - |
multiplication | * |
division | / |
power operator | ^ |
square root
Solution 1
We can create objects
by simply assigning a value to it.
For instance
= 2
x class(x)
[1] "numeric"
I created a variable x
and assigned to it the number 2
. Therefore, x
is a numeric
variable.
= "Giacomo"
x class(x)
[1] "character"
Now, assigning "Giacomo"
to x
made it a character
variable. A character variable will generally contains information in the form of letters. In Statistics, characters are generally called nominal
variables.
To create objects in R
we can use two symbols
<-
, such as x <- 2
=
, such as x = 2
The two are equivalent.
You can name your object anything. The only rule is to not start by a number. See below
# Correct
<- 30
Age <- "Natalie"
Name
# Incorrect, will generate an error
1Age = 30
2Name = "Natalie"
y
y
by 2Solution 2.
We can store more than one value in a variable.
Let’s create a variable called df
and let’s assign five values to it.
<- c(22, 27, 30, 36, 40)
df df
[1] 22 27 30 36 40
We used the assignment operator <-
to allocate the values to df
. We used the parentheses ()
separated by a comma ,
for assigning multiple values, but also c
to start the list.
We now can perform mathematical operations on this array (df
)
For instance, let’s calculate the average
mean(df)
[1] 31
We have used the R function called mean()
to calculate the average of this list.
Create an array called df_birthday
with the year of birth of five people you know.
df_birthday
df_birthday
If you do not know the name of a function, simply google it!
Solution 3.