1 Getting Started

Getting Started with R

  • When you type something into the console, R will give you a reply. For example:

    2+4
    #> [1] 6
  • As expected, R returned 6.

Note:

  • You can ignore the [1] you see in the output. It simply means that 6 is the “first element of the line.”

Getting Started with R

  • R can also be used as a calculator.

    (59 + 73 + 2) / 3
    #> [1] 44.66667
    10^(3+1)
    #> [1] 10000

Note:

  • Arithmetic operators in R are the same as in most other computer applications.

Arithmetic Operators

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)

Exercise 1.1

  • Use R to calculate the following:
    • 52
    • Add 8 to 22 and then multiply the result by 3
    • Divide 8 by 2.5 and then divide the result by 3

Notice

These calculations do not create objects that are remembered by R.

Creating Objects

  • To store calculations in R, we assign them to objects.

  • Assignment operators <- or = can be used, but <- is preferred because = has other uses.

    my_obj <- 48
  • 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).

Creating Objects

Creating Objects

  • If you switch from ‘List’ to ‘Grid’ view in the Environment tab, RStudio will show:
    • the type (e.g., numeric)
    • the length (number of values)
    • the size in memory
    • and the stored value

Creating Objects

  • Objects can hold different types of values. For example:

    my_obj2 <- "R is cool"
  • Here we created my_obj2, which stores a character string "R is cool".

Note

  • Strings must be in quotes.

  • If you forget, R will return an error.

    my_obj2 <- R is cool
    #> Error in parse(text = input): <text>:1:14: unexpected symbol
    #> 1: my_obj2 <- R is
    #>                  ^

Creating Objects

  • Our workspace now contains both my_obj and my_obj2.

Creating Objects

  • To change the value of an existing object, reassign it:

    my_obj2 <- 1024
  • Now my_obj2 holds a numeric value instead of a string.

Creating Objects

  • You can perform operations using objects. For example:

    my_obj3 <- my_obj + my_obj2
    my_obj3
    #> [1] 1072
  • This creates my_obj3 with value 48+1024=1072.

Creating Objects

  • If you try adding two character strings:

    char_obj <- "hello"
    char_obj2 <- "world!"
    char_obj3 <- char_obj + char_obj2
    #> Error in char_obj + char_obj2: non-numeric argument to binary operator
  • R will return an error because strings cannot be added.

Creating Objects

  • Another common error is object * not found.

    my_obj <- 48
    my_obj4 <- my_obj + no_obj
    #> Error: object 'no_obj' not found
  • Here, no_obj has not been created, so the operation fails.

Naming Objects

  • In R, object names are case sensitive.
  • Valid object names can include:
    • letters (a-z, A-Z)
    • digits (0-9)
    • dot . and underscore _
  • Rules:
    • Names cannot start with a number, hyphen -, or underscore _.
    • Names can start with a dot, but only if followed by a letter.
    • Non-syntactic names must be enclosed in backticks.
  • Good practice: use meaningful names for readability.
  • Avoid using names of existing R functions or keywords (mean, log, exp, TRUE, c, etc.).

Exercise 1.2

  1. Create an object x1 with value 73.
  2. Create x2 as the result of 101+36.
  3. Multiply x1 and x2 and store it in x3.
  4. Subtract 1 from x3 and calculate its 4th root.
  5. The answer should be 10.

Use of Brackets

  • Parentheses ( ) are used to group expressions. They must be matched.

    ((3 + 12)/3 + 8)
    #> [1] 13
  • Curly braces { } do not cause errors in expressions but have special uses (e.g., functions).

    {10 + 2} + 5
    #> [1] 17
  • Square brackets [ ] are used for indexing, not arithmetic:

    [2 + 7]/3
    #> Error in parse(text = input): <text>:1:1: unexpected '['
    #> 1: [
    #>     ^

R Functions

  • Functions are pre-written pieces of code.
  • Some examples:
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)

R Functions

  • General function structure:

    function_name(arg1 = val1, arg2 = val2, ...)
  • Example:

    sqrt(25)
    #> [1] 5
    sqrt(x = 25)
    #> [1] 5

Both return 5.

Note

  • Inputs (called arguments) go inside parentheses ( ).
  • Multiple arguments are separated by commas.

Some Useful Built-in Functions

round(3.567, digits=2)
#> [1] 3.57
floor(3.567)
#> [1] 3
ceiling(3.567)
#> [1] 4
pi   # Not a function, but useful
#> [1] 3.141593

R Ignores Extra Spaces

(1+2)     ^     3
#> [1] 27
    ( 1+  2)    ^ 3
#> [1] 27
  • You can add spaces freely between elements.

  • But spaces inside a value cause errors:

    3   .14
    #> Error in parse(text = input): <text>:1:5: unexpected numeric constant
    #> 1: 3   .14
    #>         ^

Commenting Code

Use # to write comments. R ignores everything after #.

# Calculating BMI
weight <- 70   # in kg
height <- 1.7  # in meters
bmi <- weight / height ^ 2
bmi
#> [1] 24.22145

Running R Scripts

Instead of typing code line by line, you can save it in a script (.R file).

From R Console:

source("my_script.R")

Note

  • Make sure the script file is saved in your current working directory.
  • If it’s in another folder, provide the full file path.
  • Example: source("C:/Users/Rasel/Documents/my_script.R")

From Terminal:

Rscript my_script.R

Tip

  • source() runs inside your current R session (objects remain).
  • Rscript runs in a fresh session (objects do not remain).

Exercise 1.3

Why does this code not work?

my_variable <- 10
my_varıable
#> Error: object 'my_varıable' not found

Exercise 1.4

  1. Create an object myObject with a value between 1 and 100.
  2. Add 13 to myObject and update the object.
  3. Check if myObject is divisible by 2, 3, 13, or 21.
  4. How many times can 5 fit into myObject?

Exercise 1.5

  1. Save this code into practice.R:

    x <- 5
    y <- 10
    print(x + y)
  2. Run it with source("practice.R") (R Console).

  3. Run it with Rscript practice.R (Terminal).

1 / 26
1 Getting Started

  1. Slides

  2. Tools

  3. Close
  • 1 Getting Started
  • Getting Started with R
  • R can also be used...
  • Arithmetic Operators
  • Exercise 1.1
  • Creating Objects
  • Slide 7
  • If you switch from...
  • Objects can hold...
  • Our workspace now...
  • To change the value...
  • You can perform operations...
  • If you try adding...
  • Another common error...
  • Naming Objects
  • Exercise 1.2
  • Use of Brackets
  • R Functions
  • General function...
  • Some Useful Built-in Functions
  • R Ignores Extra Spaces
  • Commenting Code
  • Running R Scripts
  • Exercise 1.3
  • Exercise 1.4
  • Exercise 1.5
  • f Fullscreen
  • s Speaker View
  • o Slide Overview
  • e PDF Export Mode
  • r Scroll View Mode
  • ? Keyboard Help