3 Introduction of R and R studio

3.1 Getting Started

3.2 Helps

3.3 Quick tour of Rstudio

  • There are four panels
    1. Source: Write your own code here.
    2. Console:
    3. Environment/History:
    4. Files/Plots/Packages/Help:
  • In the Source panel,
    • Write your own code.
    • Save your code in .R file
    • Click Run command to run your entire code.
  • In the concole panel,
    • After clicking Run in the source panel, your code is evaluated.
    • You can directly type your code here to implement.

3.4 Basic Calculations

To get started, we’ll use R like a simple calculator.

Addition, Subtraction, Multiplication and Division

Math R Result
\(3 + 2\) 3 + 2 5
\(3 - 2\) 3 - 2 1
\(3 \cdot2\) 3 * 2 6
\(3 / 2\) 3 / 2 1.5

Exponents

Math R Result
\(3^2\) 3 ^ 2 9
\(2^{(-3)}\) 2 ^ (-3) 0.125
\(100^{1/2}\) 100 ^ (1 / 2) 10
\(\sqrt{100}\) sqrt(100) 10

Mathematical Constants

Math R Result
\(\pi\) pi 3.1415927
\(e\) exp(1) 2.7182818

Logarithms

  • Note that we will use \(\ln\) and \(\log\) interchangeably to mean the natural logarithm.
  • There is no ln() in R, instead it uses log() to mean the natural logarithm.
Math R Result
\(\log(e)\) log(exp(1)) 1
\(\log_{10}(1000)\) log10(1000) 3
\(\log_{2}(8)\) log2(8) 3
\(\log_{4}(16)\) log(16, base = 4) 2

Trigonometry

Math R Result
\(\sin(\pi / 2)\) sin(pi / 2) 1
\(\cos(0)\) cos(0) 1

3.5 Getting Help

  • In using R as a calculator, we have seen a number of functions: sqrt(), exp(), log() and sin().
  • To get documentation about a function in R, simply put a question mark in front of the function name and RStudio will display the documentation, for example:
?log
?sin
?paste
?lm

3.6 Installing Packages

  • One of the main strengths of R as an open-source project is its package system.
  • To install a package, use the install.packages() function.
    • Think of this as buying a recipe book from the store, bringing it home, and putting it on your shelf.
install.packages("ggplot2")
  • Once a package is installed, it must be loaded into your current R session before being used.
    • Think of this as taking the book off of the shelf and opening it up to read.
library(ggplot2)
  • Once you close R, all the packages are closed and put back on the imaginary shelf.
  • The next time you open R, you do not have to install the package again, but you do have to load any packages you intend to use by invoking library().