1 Getting Started with R

Author
Affiliation

Md Rasel Biswas

IASDS, University of Dhaka

1 Learning objectives

By the end of this lecture, you should be able to:

  • use R as a calculator;
  • create, inspect, and update objects;
  • follow basic object-naming rules;
  • call functions and supply arguments;
  • interpret common error messages; and
  • write and run a short R script.

2 Using the Console

Type an expression in the Console and press Enter:

2 + 4
#> [1] 6

R returns the result.

What does [1] mean?

[1] indicates that the displayed line begins with the first element of the result. It is not part of the answer.

3 R as a calculator

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

3.1 Arithmetic operators

Operation Operator Example
Addition + 8 + 3
Subtraction - 8 - 3
Multiplication * 8 * 3
Division / 8 / 3
Exponentiation ^ or ** 8^3
Integer division %/% 10 %/% 3 gives 3
Remainder %% 10 %% 3 gives 1
Write readable code

Use spaces around operators: write height ^ 2, not height^2.

4 Exercise 1.1

Use R to calculate:

  1. \(5^2\);
  2. add 8 to 22 and multiply the result by 3;
  3. divide 8 by 2.5, then divide the result by 3; and
  4. the quotient and remainder when 47 is divided by 6.
Notice

These expressions produce results, but R does not remember them unless we assign them to objects.

5 Creating objects

Use the assignment operator <- to store a value:

my_obj <- 48
my_obj
#> [1] 48

The object appears in the Environment pane and remains available during the current R session.

= can also assign values, but this course will use <- for assignment.

6 Updating and using objects

Reassigning an object replaces its previous value:

my_obj <- 50
my_obj
#> [1] 50

Objects can be used in later calculations:

bonus <- 5
final_score <- my_obj + bonus
final_score
#> [1] 55

7 Basic value types

student_count <- 45
course_name <- "R for Data Science"
is_required <- TRUE
Type Example
Numeric 45, 3.5
Character "R for Data Science"
Logical TRUE, FALSE

Character values must be enclosed in quotation marks.

course_name <- R for Data Science
#> Error in parse(text = input): <text>:1:18: unexpected 'for'
#> 1: course_name <- R for
#>                      ^

8 Naming objects

R object names are case-sensitive: score, Score, and SCORE are different names.

A valid name may contain letters, numbers, . and _, but it cannot begin with a number or _.

Use meaningful snake_case names:

student_score <- 82
class_average <- 74.5

Avoid unclear names such as a, x1, or temp2 unless their meaning is obvious from the context.

Also avoid replacing common function names:

mean <- 10
c <- 5

9 Exercise 1.2

  1. Create x1 with value 73.
  2. Create x2 as the result of \(101 + 36\).
  3. Multiply x1 and x2, and store the result in x3.
  4. Subtract 1 from x3 and calculate the fourth root.
  5. Confirm that the answer is 10.

10 Parentheses and brackets

Use parentheses to control the order of operations:

(3 + 12) / 3 + 8
#> [1] 13

Parentheses must be matched:

(3 + 12
#> Error in parse(text = input): <text>:2:0: unexpected end of input
#> 1: (3 + 12
#>    ^

Square brackets [ ] have a different purpose: they are used to select elements from an object. We will study them later.

11 Functions and arguments

A function is a reusable piece of code that performs a task.

sqrt(225)
#> [1] 15
log(50)
#> [1] 3.912023
abs(-10)
#> [1] 10
factorial(6)
#> [1] 720

The general form is:

function_name(argument1, argument2, ...)

Arguments may be supplied by position or by name:

round(3.567, 2)
#> [1] 3.57
round(x = 3.567, digits = 2)
#> [1] 3.57

Both calls return the same result.

12 Some useful built-in functions

floor(3.567)
#> [1] 3
ceiling(3.567)
#> [1] 4
exp(1)
#> [1] 2.718282
pi
#> [1] 3.141593
Function or object?

Functions use parentheses, such as sqrt(25). The value pi is an object, so it is written without parentheses.

13 Reading error messages

Errors are part of programming. Read the message and identify the line that caused it.

13.1 Object not found

my_obj + no_obj
#> Error:
#> ! object 'no_obj' not found

R cannot find no_obj because it has not been created.

13.2 Incompatible operation

"hello" + "world"
#> Error in `"hello" + "world"`:
#> ! non-numeric argument to binary operator

The + operator is defined for numbers, not character strings.

13.3 A difficult-to-see spelling error

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

The two names look similar, but the second contains a different character.

14 Comments

Use # to explain code. R ignores everything after # on that line.

# Calculate body mass index
weight <- 70   # kilograms
height <- 1.70 # metres
bmi <- weight / height^2
bmi
#> [1] 24.22145

Comments should explain the purpose of the code, not restate every symbol.

15 Writing and running an R script

A script is a plain-text file with the extension .R.

A simple workflow is:

  1. create a new script using File > New File > R Script;
  2. write and save the code inside the project;
  3. run the current line or selection using Ctrl/Cmd + Enter; and
  4. inspect the output in the Console.

To run an entire script from R:

source("scripts/my_script.R")

source() runs the script in the current R session.

16 A first data object

A vector stores several values of the same basic type. Use c() to combine values:

scores <- c(72, 81, 65, 90, 77)
scores
#> [1] 72 81 65 90 77

We can now summarize the data:

length(scores)
#> [1] 5
mean(scores)
#> [1] 77
min(scores)
#> [1] 65
max(scores)
#> [1] 90

This pattern—create an object, apply a function, inspect the result—is central to working with data in R.

17 Exercise 1.3

Create the vector:

study_hours <- c(2, 4, 3, 5, 6)

Then calculate:

  1. the number of students;
  2. the average study time;
  3. the minimum and maximum study time; and
  4. the total study time.

18 Exercise 1.4

  1. Create an object my_number with an integer between 1 and 100.
  2. Add 13 and update my_number.
  3. Check the remainder after division by 2, 3, 13, and 21.
  4. Use integer division to find how many complete groups of 5 can be formed.
  5. Add comments explaining each step.

19 Key points

  • Use <- to assign values to objects.
  • Use meaningful, case-consistent object names.
  • Functions take inputs inside parentheses.
  • Error messages help identify problems in code.
  • Save analysis steps in scripts rather than relying on Console history.