2.6 Let’s get started with R
2.6.1 R as a calculator
2.6.1.1 Simple calculations
R
can be used as a calculator. Try some of the following below:
## [1] 3
## [1] 7
Well wait a second! were you all expecting the result to be 7? how many expected the result to be 9?
Check the following:
## [1] 9
## [1] 7
So parenthesis are important! Always use these to tell R (and any other software) the order of operations. This is the order (remember PEMDAS):
- Parentheses
- Exponents
- Multiplication and Division (from left to right)
- Addition and Subtraction (from left to right)
2.6.1.2 Functions
There are many built-in functions in R to do some complicated mathematical calculations.
2.6.1.2.1 Basic functions
Run some of the following.
## [1] 1.732051
## [1] 9
## [1] 1.098612
## [1] 20.08554
2.6.2 Objects
2.6.2.1 Basic objects
Objects are related to variables (we created above), but can also be dataframes, and other things we create in R. All of these are stored in memory and are shown below (under environment). You can check the type of the “object” below in the list (look at “Type”) or by using class()
.
Let’s look at the variables we created so far.. We will create another one as well…
## [1] "numeric"
## [1] "numeric"
## [1] "numeric"
## [1] "integer"
## [1] "numeric"
## [1] "character"
When we do calculations in R, we need to make sure we use numeric/integer variables only.. Try some of the below. Uncomment the following ##x + two
and run the code.
## [1] 7
Can you explain the error?
We have tried to add a number to a (character) string which is clearly impossible.
To do the maths, we need to change the class using any of the following commands: as.character
, as.integer
, as.numeric
, as.factor
, e.g.:
## [1] 4
2.6.2.2 Other functions and objects
2.6.2.2.1 Some more calculations
We can create a vector of objects to do various things on.. We use the function c()
and do various things on:
## [1] "numeric"
## [1] 148.0909
## [1] 276.6375
## [1] 38
## [1] 1
## [1] 836
## [1] 1 836
## [1] 1629
2.6.2.2.2 Referring to a specific position
Sometimes we may want to refer to a specific position in the list of numbers we just created… Use the following:
## [1] 4
## [1] 5 12 55
## [1] 1 4 5 55 13 45 38 77 836 543
## [1] 14 17 18 25 68 26 58 51 90 849 556
Can you explain what we have done in the last operation?