Back to Course
Basics

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

TypeExampleDescription
numeric3.14, 100Decimal (double) or whole numbers
integer5LWhole numbers (suffix L forces integer type)
character"hello"Text / strings
logicalTRUE, FALSEBoolean values
complex2+3iComplex 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 — Age and age are different variables.
  • Cannot use reserved words like TRUE, if, or function.
# 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

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 22.5
^ or **Exponent2 ^ 38
%%Modulus (remainder)5 %% 21
%/%Integer division5 %/% 22

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.

Explore Course