Goal of This Chapter
Before doing real data science, you must understand:
- How R reads code
- What each symbol means (
<-,->,=,:,$,%>%,==, etc.) - How to write proper R statements
- How to avoid beginner errors
This chapter explains EVERYTHING clearly.
How R Executes Code
R is an interpreted language, meaning:
You write code → R reads it line by line → R produces output
Try this:
10 + 5
Output:
[1] 15
Comments in R
Comments are notes for humans, ignored by R.
# This is a comment
x <- 10 # comment after code
Used for:
- Documentation
- Explaining code
- Improving readability
Assignment Operators.
Assignment means: store a value inside a variable.
R has 3 assignment operators. We explain them fully.
Left Assignment <-
This is the standard, recommended assignment operator in R.
value → variable (visual idea)
But written in R as:
x <- 10
Meaning: Put 10 into x.
✔ Preferred in data science
✔ Used in all textbooks
✔ Used in tidyverse
Equal Sign =
Same meaning as <-, but less preferred.
x = 20
Used mainly inside functions.
Example:
mean(x = c(1,2,3))
Right Assignment ->
Same as <- but reversed.
value → variable
Example:
30 -> y
Meaning: Put 30 into y.
Used rarely, but helpful in pipelines.
Explanation of Common Symbols in R
Assignment operator <-
x <- 5
Store 5 in x.
Right-side assignment ->
10 -> a
Stores 10 in variable a.
Assignment (alternate form) =
b = 15
Stores 15 in b.
Sequence operator :
Creates numbers from A to B.
1:5
Output:
[1] 1 2 3 4 5
Access column inside a data frame $
If you have a dataset:
df$age
This extracts the age column.
Comparison operator (equal to) ==
5 == 5 # TRUE
5 == 4 # FALSE
Used in filtering data.
Not equal to ! =
5 != 4 # TRUE
Comparison operators >, <, >= ,<=
10 > 3 # TRUE
3 >= 3 # TRUE
Pipe Operator (VERY IMPORTANT) %>%
This sends output of one function into the next function.
Example:
library(dplyr)
iris %>% head()
Meaning:
Take iris → then apply head()
This operator is the HEART of modern R programming.
Indexing operator [ ]
x <- c(10,20,30,40)
x[2]
Output:
[1] 20
Function call operator ( )
Everything in R is a function.
sum(1:5)
mean(c(10,20,30))
Statements and Expressions
Expression = produces a value
3 + 4
sqrt(49)
Statement = does an action
x <- 25
print(x)
Printing Output
Two main ways:
1. Automatic printing (Console)
10 + 20
2. Explicit printing
print("Hello R")
Errors and Messages (Understanding Output)
Example Error
x <- 10
x + "hello"
Output:
Error: non-numeric argument to binary operator
Meaning: You cannot add numbers + text.
Coding Exercises (Must Do)
Exercise 1
Create variables using all 3 assignment operators.
Exercise 2
Use sequence : to make numbers from 50 to 80.
Exercise 3
Extract 3rd element from:
v <- c(100,200,300,400)
Exercise 4
Use $ to extract a column from mtcars