Assigning Variables in R
Programming
● Understanding Variable
Assignment in R
● Vigyat | Semester 4
● 92300527222
Introduction
●- Variables store data values.
●- In R, variables don’t need explicit declaration.
●- Assigned using `<-`, `=`, or `assign()` function.
Syntax of Variable
Assignment
●x <- 10 # Preferred assignment
●y = "Hello" # Alternative method
●assign("z", 3.14) # Using assign() function
●- `<-` is the most commonly used
operator.
●- `=` works but is less recommended.
●- `assign()` dynamically assigns values.
Naming Rules for
Variables
●✅ Can contain letters, numbers, underscores
●✅ Case-sensitive (`var1` ≠ `Var1`)
●❌ Cannot start with a number (e.g., `1var` is
invalid)
●❌ Cannot use reserved words (e.g., `if`,
`for`)
Example
●num <- 25 # Numeric
●text <- "R Language" # Character
●flag <- TRUE # Logical
●vec <- c(1, 2, 3) # Vector
●- R is dynamically typed; no need to
specify data type.
Checking Variable Type
●class(num) # "numeric"
●class(text) # "character"
●class(flag) # "logical"
- Use `class()` to check the data
type of a variable.
Reassigning Variables
●x <- 10
●x <- "New Value" # Changes from
numeric to character
●R allows dynamic type changes.
Removing Variables
●rm(x) # Removes variable x
●rm(list = ls()) # Clears all variables
from the environment
●- Use `rm()` to delete variables.
●- `ls()` lists all variables.
Summary
●- `<-` is the recommended
assignment operator.
●- Variables can hold different data
types.
●- Use `class()` to check types and
`rm()` to remove variables.