Variables, Data Types, and Basic Operations
Before working with real datasets, you need a solid grasp of how R stores and manipulates individual pieces of data. This starts with variables and R's core atomic data types.
1. Creating Variables — The Assignment Operator
R conventionally uses <- for assignment (though = also works in most contexts):
age <- 25
name <- "Alice"
is_active <- TRUE
print(age)
Pro Tip: Use <- for assignment, not =. It's the R community standard and avoids ambiguity inside function calls like mean(x = 1:10).
2. Basic Data Types
| Type | Example | Description |
|---|---|---|
| numeric | 3.14, 100 | Decimal (double) or whole numbers |
| integer | 5L | Whole numbers (suffix L forces integer type) |
| character | "hello" | Text / strings |
| logical | TRUE, FALSE | Boolean values |
| complex | 2+3i | Complex numbers (rarely used) |
num_val <- 42.5 # numeric
int_val <- 42L # integer
char_val <- "R lang" # character
log_val <- TRUE # logical
class(num_val) # "numeric"
class(int_val) # "integer"
typeof(char_val) # "character"
3. Checking and Converting Types
Use class() or typeof() to inspect, and as.*() functions to convert:
x <- "10"
class(x) # "character"
y <- as.numeric(x) # convert to numeric
class(y) # "numeric"
z <- as.character(25)
class(z) # "character"
4. Naming Rules for Variables
- Must start with a letter or a dot (not followed by a number).
- Can contain letters, numbers, dots, and underscores.
- Case-sensitive —
Ageandageare different variables. - Cannot use reserved words like
TRUE,if, orfunction.
# Valid names
my_var <- 1
.hidden_var <- 2
total2 <- 3
# Invalid names
# 2total <- 1 # cannot start with a number
# my-var <- 1 # hyphens not allowed
5. Basic Arithmetic Operations
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 5 / 2 | 2.5 |
| ^ or ** | Exponent | 2 ^ 3 | 8 |
| %% | Modulus (remainder) | 5 %% 2 | 1 |
| %/% | Integer division | 5 %/% 2 | 2 |
6. Logical and Comparison Operators
5 > 3 # TRUE
5 == 5 # TRUE
5 != 3 # TRUE
TRUE & FALSE # FALSE (AND)
TRUE | FALSE # TRUE (OR)
!TRUE # FALSE (NOT)
Common Issues: Use == for comparison, not =. A single = inside an expression is a common beginner mistake that causes confusing errors.
7. Production-Ready Checklist
- ✅ Use <- for assignment — the R idiomatic style.
- ✅ Know the five atomic types — numeric, integer, character, logical, complex.
- ✅ Convert types explicitly — with as.numeric(), as.character(), etc.
- ✅ Follow variable naming rules — descriptive, snake_case names are conventional.
Pro Tip: Getting comfortable with types now prevents confusing bugs later — e.g., trying to do math on a variable that's secretly stored as text.
Ready to master R Programming?
Build real-world data analysis and visualization projects with hands-on training, mentor-led sessions, and placement support.
.png)