2 + 4
#> [1] 61 Getting Started with R
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:
R returns the result.
[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] 100003.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
|
Use spaces around operators: write height ^ 2, not height^2.
4 Exercise 1.1
Use R to calculate:
- \(5^2\);
- add 8 to 22 and multiply the result by 3;
- divide 8 by 2.5, then divide the result by 3; and
- the quotient and remainder when 47 is divided by 6.
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] 48The 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] 50Objects can be used in later calculations:
bonus <- 5
final_score <- my_obj + bonus
final_score
#> [1] 557 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.5Avoid 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 <- 59 Exercise 1.2
- Create
x1with value 73. - Create
x2as the result of \(101 + 36\). - Multiply
x1andx2, and store the result inx3. - Subtract 1 from
x3and calculate the fourth root. - Confirm that the answer is 10.
10 Parentheses and brackets
Use parentheses to control the order of operations:
(3 + 12) / 3 + 8
#> [1] 13Parentheses 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.
The general form is:
function_name(argument1, argument2, ...)Arguments may be supplied by position or by name:
Both calls return the same result.
12 Some useful built-in functions
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 foundR 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 operatorThe + 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 foundThe two names look similar, but the second contains a different character.
15 Writing and running an R script
A script is a plain-text file with the extension .R.
A simple workflow is:
- create a new script using File > New File > R Script;
- write and save the code inside the project;
- run the current line or selection using Ctrl/Cmd + Enter; and
- 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 77We can now summarize the data:
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:
- the number of students;
- the average study time;
- the minimum and maximum study time; and
- the total study time.
18 Exercise 1.4
- Create an object
my_numberwith an integer between 1 and 100. - Add 13 and update
my_number. - Check the remainder after division by 2, 3, 13, and 21.
- Use integer division to find how many complete groups of 5 can be formed.
- 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.
14 Comments
Use
#to explain code. R ignores everything after#on that line.Comments should explain the purpose of the code, not restate every symbol.